单行检查列表中的至少一项是否存在于另一个列表中? [英] one-liner to check if at least one item in list exists in another list?
问题描述
假设我有一个清单a=[1,2,3]
我想知道其中是否至少有一个数字存在于另一个列表中,例如:b=[4,5,6,7,8,1]
换句话说,我想知道列表 b
中是否存在 1,2 或 3 个.我现在可以做类似的事情
Lets say I have a list
a=[1,2,3]
And I want to know if at least one of the numbers in it exist in another list, like this one:
b=[4,5,6,7,8,1]
In other words, I want to know if 1,2 or 3 exist(s) in list b
.
I now I could do something like
def func(a, b):
for i in a:
if i in b:
return True
return False
但是有没有办法把它放在一行中让事情变得整洁?
But is there possibly a way to put that in one line to make things tidy?
推荐答案
有很多方法可以做到这一点.最直接的翻译是:
There are many ways to do this. The most direct translation is:
any_in = lambda a, b: any(i in b for i in a)
您还可以使用各种涉及集合的东西,例如:
You could also use various things involving sets, such as:
any_in = lambda a, b: bool(set(a).intersection(b))
(这取决于 a
的元素是否可以散列,但如果这是真的,从 a
和b
适用于这些方法中的任何一种).
(which depends on the elements of a
being hashable, but if that's true, it'll probably be faster to make a set of the larger out of a
and b
for either of these approaches).
对于 Python 2.6 及更高版本,isdisjoint
比 intersection
更好,正如下面不同的人所指出的.很高兴了解这一点.:)
isdisjoint
is better than intersection
for Python 2.6 and above, as noted by various people below. Glad to learn about that. :)
这篇关于单行检查列表中的至少一项是否存在于另一个列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!