hypersonics
hypersonics

Reputation: 1134

Using iterator over a list within the if statement in Python

I am using a function to read a particular file, which in this case is options and do some regex for every line I read. The file I am reading is:

EXE_INC = \
    -I$(LIB_SRC)/me/bMesh/lnInclude \
    -I$(LIB_SRC)/mTools/lnInclude \
    -I$(LIB_SRC)/dynamicM/lnInclude

My code is

def libinclude():
    with open('options', 'r') as options:
    result = []
    for lines in options:
        if 'LIB_SRC' in lines and not 'mTools' in lines:
            lib_src_path = re.search(r'\s*-I\$\(LIB_SRC\)(?P<lpath>\/.*)', lines.strip())
            lib_path = lib_src_path.group(1).split()
            result.append(lib_path[0])
            print result
return (result)

Now as you can see, I look for the line that has mTools and filter using not 'mTools' in lines. However, when I have many such strings how do I filter? Say, for example, I would like to filter the lines that has mTools and dynamicM. Is it possible to put such strings in a list and then access the elements of that list against lines in the if statement?

Upvotes: 0

Views: 61

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65791

Yes, you can use the built-in function all():

present = ['foo', 'bar', 'baz']
absent = ['spam', 'eggs']
for line in options:
    if all(opt in line for opt in present) and all(
           opt not in line for opt in absent):
       ...

See also: any().

Upvotes: 1

Related Questions