这个问题的反面(在列表中查找字符串)非常受欢迎,以至于我无法找到我的问题的答案。
black_list = ["ab:", "cd:", "ef:", "gh:"]
for line in some_file:
if ":" in line and black_list not in line:
pass
这显然是行不通的。需要对列表进行一些迭代以返回真/假,但我不知道如何优雅地完成它。谢谢。
这个问题的反面(在列表中查找字符串)非常受欢迎,以至于我无法找到我的问题的答案。
black_list = ["ab:", "cd:", "ef:", "gh:"]
for line in some_file:
if ":" in line and black_list not in line:
pass
这显然是行不通的。需要对列表进行一些迭代以返回真/假,但我不知道如何优雅地完成它。谢谢。
内置any()
函数可以在这里为您提供帮助:
black_list = ["ab:", "cd:", "ef:", "gh:"]
for line in some_file:
if ":" in line and not any(x in line for x in black_list):
pass
也可以通过以下方式获得相同的效果all()
:
for line in some_file:
if ":" in line and all(x not in line for x in black_list):
pass
...但我认为第一个更接近英语,所以更容易理解。
您的示例代码看起来像是在文件中查找元素,而不仅仅是在字符串中。无论如何,你可以做这样的事情,这说明了用内置any()
函数做这两个:
def check_string(text, word_list):
return any(phrase in text for phrase in word_list)
def check_file(filename, word_list):
with open(filename) as some_file:
return any(check_string(line, word_list) for line in some_file)
black_list = ["ab:", "cd:", "ef:", "gh:"]
print check_file('some_file.txt', black_list)
您可以检查 black_list 中的每个“标志”,并过滤包含 black_list 的行。这可以使用all()
:
for line in some_file:
filtered = all(i in line for i in black_list)
if filtered and ':' in line:
# this line is black listed -> do something
else:
# this line is good -> do something
以上检查是否存在 black_list 的所有元素。使用any()
, 如果您想在 black_list 的任何元素存在时拒绝一行:
for line in some_file:
filetered = any(i in line for i in black_list_2)
if filtered:
# this line contains at least one element of the black_list
else:
# this line is fine