Yil*_*ang 11 python list match
我正在尝试使用python进行匹配.
我有一个字符串列表(len~3000)和一个文件,我想检查文件中的每一行是否至少有一个列表中的字符串.
最直接的方法是逐个检查,但需要时间(不过很长时间).
有没有办法可以更快地搜索?
例如:
list = ["aq", "bs", "ce"]
if the line is "aqwerqwerqwer" -> true (since has "aq" in it)
if the line is "qweqweqwe" -> false (has none of "aq", "bs" or "ce")
Run Code Online (Sandbox Code Playgroud)
iCo*_*dez 16
# Please do not name a list "list" -- it overrides the built-in
lst = ["a", "b", "c"]
if any(s in line for s in lst):
# Do stuff
Run Code Online (Sandbox Code Playgroud)
上面的代码将测试是否lst
可以找到任何项目line
.如果是这样,# Do stuff
将会运行.
请参阅下面的演示:
>>> lst = ["aq", "bs", "ce"]
>>> if any(s in "aqwerqwerqwer" for s in lst):
... print(True)
...
True
>>> if any(s in "qweqweqwe" for s in lst):
... print(True)
...
>>>
Run Code Online (Sandbox Code Playgroud)