如何检查列表中的元素是否在字符串中

时间:2013-07-23 00:14:51

标签: python string list if-statement element

这个问题的反面(在列表中找到一个字符串)非常受欢迎,我无法找到问题的答案。

black_list = ["ab:", "cd:", "ef:", "gh:"]

for line in some_file:
    if ":" in line and black_list not in line:
        pass

这显然不起作用。需要在列表上进行一些迭代才能返回true / false,但我不知道如何优雅地完成它。感谢。

3 个答案:

答案 0 :(得分:6)

内置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

...但我认为第一个更接近英语,因此更容易理解。

答案 1 :(得分:0)

您可以检查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的所有元素。如果您想要在存在black_list的任何元素时拒绝某一行,请使用any()

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

答案 2 :(得分:0)

您的示例代码使您看起来像是在文件中查找元素,而不仅仅是在字符串中。无论如何,你可以做这样的事情,这说明了使用内置的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)