[Tutor] list comprehension, testing for multiple conditions

Alan Gauld alan.gauld at btinternet.com
Wed Aug 22 09:36:56 CEST 2012


On 22/08/12 08:06, Peter Otten wrote:

> You can even have multiple if clauses in one list-comp (but that is rarely
> used):
>
> with open(filename) as lines:
>      wanted = [line.strip("\n") for line
>                    if "vn" not in line
>                    if "vt" not in x
>                    if line != "\n"]
>
> While your problem is simple enough to combine all filters into one list-
> comp some problems are not. You can then prevent the intermediate lists from
> materializing by using generator expressions. The result minimizes memory
> consumption, too, and should be (almost) as fast. For example:
>
> with open(filename) as lines:
>      # use gen-exps to remove empty and whitespace-only lines
>      stripped = (line.strip() for line in lines)
>      nonempty = (line for line in stripped if line)
>
>      wanted = [line for line in nonempty
>                    if "vt" not in line and "vn" not in line]

Another option using generators is to roll your own. This would be my 
recomendation for really complex filtering:

def myFilterGenerator(aFile):
     for line in aFile:
         if 'vn' not in line:   # demo "complexity" not efficiency!
            if 'vt' not in line:
                if '\n' != line:
                   yield line.strip()

with open filename as myFile:
     result = [line for line in myFilterGenerator(myFile)]


But in this specific case the filter is simple enough that the
list comp from Peter is probably the best solution.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list