Python 如何检查列表中的元素是否在字符串中
这个问题的反义词(在列表中查找字符串)非常流行,以至于我无法找到问题的答案Python 如何检查列表中的元素是否在字符串中,python,string,list,if-statement,element,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的迭代,但我不知道如何优雅地完成这一点。谢谢。内置功能可以帮助您: black_list = ["ab:", "c
black_list = ["ab:", "cd:", "ef:", "gh:"]
for line in some_file:
if ":" in line and black_list not in line:
pass
这显然行不通。需要对列表进行一些返回true/false的迭代,但我不知道如何优雅地完成这一点。谢谢。内置功能可以帮助您:
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()
完成:
以上检查是否存在黑名单中的所有元素。使用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
您的示例代码使其看起来像是在文件中查找元素,而不仅仅是在字符串中。无论如何,您可以这样做,这说明了如何使用内置的
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)
可能是一个正则表达式,或者如果通过“字符串”引用一个短语,则将其拆分为一个数组,然后查看是否可以匹配其任何元素?能否给出一个简短的示例,说明您需要什么输入和输出?因为中的
运算符总是返回布尔值,True if in line else False
有点多余:对于给定的情况,这类似于说True if else False
或True if False else False
@ZeroPiraeus,谢谢你我没有意识到这一点。将编辑相应的好点,@ZeroPiraeus。不过请注意,这并不是因为
中的总是返回bool,而是因为any()
被定义为“如果bool(x)对iterable中的任何x为真,则返回True”——换句话说,any()
与if/else做了等价的事情。@BenHoyt是的,这也有:-)哦,还有@NickBurns-仔细看,您的答案不太正确:OP想检查字符串中是否有“:”,但黑名单中没有一项是正确的。您的解决方案检查字符串中是否有“:”,以及黑名单中的所有项目是否都是。这正是我希望看到的,又好又短。
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
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)