检查两个列表是否共享至少一个元素 [英] Checking if two lists share at least one element
问题描述
例如,我有两个列表:
a = ["mail1", "mail2", "mail3", "mail4"]
b = ["mail2", "mail5"]
,我想检查列表b
中的任何元素是否也出现在列表a
中.
and I want to check if any of the elements in list b
also appears in list a
.
我想知道是否有一种方法(及其作用)没有for循环.
I wanted to know if there is a way (and what is it) to do this without a for loop.
我还想知道如何创建一个布尔值列表,其中每个值都是值a[i]
和b[i]
的比较结果,例如:
Also I wanted to know how can I create a list of boolean values, where each value will be the result of the comparison of values a[i]
and b[i]
, something like:
[z for i, j in zip(a, b) z = i == j] # (just with the right syntax)
如果在某些地方i == j
,
z
将为1
,因此我可以检查数组中是否有任何'True'值.
z
will be 1
if in some place i == j
, so I can check the array for any 'True' values.
推荐答案
您可以使用any
:
any(x in a for x in b)
关于此生成器表达式的好处是,any
将在生成器生成True
后立即返回True
,即不会有多余的x in a
查找.
The nice thing about this generator expression is that any
will return True
as soon as the generator yields a True
, i.e. there won't be redundant x in a
lookups.
关于您的新问题:
[x == y for x,y in zip(a,b)]
这篇关于检查两个列表是否共享至少一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!