我正在使用一个函数来读取一个特定的文件,在本例中是options
,并对我读取的每一行执行一些正则表达式。我正在阅读的文件是:
EXE_INC =
-I$(LIB_SRC)/me/bMesh/lnInclude
-I$(LIB_SRC)/mTools/lnInclude
-I$(LIB_SRC)/dynamicM/lnInclude
我的代码是
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)
现在,正如您所看到的,我查找具有mTools
并使用not 'mTools' in lines
进行筛选的行。然而,当我有很多这样的字符串时,我该如何过滤?例如,我想过滤具有mTools
和dynamicM
的行。是否可以将这些字符串放入列表中,然后根据if
语句中的lines
访问该列表的元素?
是的,您可以使用内置函数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):
...
另请参见:any()
。