简体   繁体   English

如何检查列表中的任何项是否出现在另一个列表中?

[英]How to check if any item in a list occurs in another list?

If I have the following list: 如果我有以下列表:

listA = ["A","Bea","C"]

and another list 和另一个清单

listB = ["B","D","E"]
stringB = "There is A loud sound over there"

What is the best way to check if any item in listA occurs in listB or stringB, if so then stop? 检查listA中的任何项是否出现在listB或stringB中的最佳方法是什么,如果是,那么停止? I typically use for loop to iterate over each item in listA to do such a thing, but are there better ways syntactically? 我通常使用for循环迭代listA中的每个项目来做这样的事情,但是语法上有更好的方法吗?

for item in listA:
    if item in listB:
        break;

For finding the overlap of two lists, you can do: 要查找两个列表的重叠,您可以执行以下操作:

len(set(listA).intersection(listB)) > 0

In if statements you can simply do: if语句中,您可以简单地执行:

if set(listA).intersection(listB):

However, if any items in listA are longer than one letter, the set approach won't work for finding items in stringB , so the best alternative is: 但是,如果listA中的任何项长于一个字母,则set方法将无法用于查找stringB项,因此最佳替代方法是:

any(e in stringB for e in listA)

You can use any here: any will short-circuit and will stop at the first match found. 你可以在这里使用anyany会短路,并将在找到的第一场比赛时停止。

>>> listA = ["A","B","C"]
>>> listB = ["B","D","E"]
>>> stringB = "There is A loud sound over there"
>>> lis = stringB.split()
>>> any(item in listA or item in lis for item in listA) 
True

If listB is huge or the list returned from stringB.split() is huge then you should convert them to sets first to improve complexity: 如果listB很大或者从stringB.split()返回的列表很大,那么你应该首先将它们转换为sets以提高复杂性:

>>> se1 =  set(listB)
>>> se2 = set(lis)
>>> any(item in se1 or item in se2 for item in listA)
True

If you're searching for multiple words inside that string then use regex : 如果您在该字符串中搜索多个单词,请使用regex

>>> import re
>>> listA = ["A","B","C"]
>>> listB = ["B","D","E"]
>>> stringB = "There is A loud sound over there"
>>> any(item in listA or re.search(r'\b{}\b'.format(item),stringB)
                                                              for item in listA) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM