查找列表中的任何元素是否在另一个列表中并返回找到的第一个元素 [英] Finding if any element in a list is in another list and return the first element found
问题描述
使用any()
很容易检查一个列表的元素是否在另一个列表中:
any(elem in list2 for elem in list1)
但是无论如何都有返回找到的第一个元素的惯用方法吗?
我更喜欢单行解决方案而不是:
对于列表 1 中的元素:如果列表 2 中的元素:返回元素
这个答案类似于 关于类似问题的答案,与其他算法相比,@jamylak 更详细地介绍了结果计时.
如果您只想要匹配的第一个元素,请使用 下一步
:
这不是太有效,因为它对每个元素执行 b
的线性搜索.您可以从 b
创建一个 set
,它具有更好的查找性能:
如果 next
没有找到任何东西,它会引发异常:
你可以给它一个默认的返回值,例如无
.但是,这会改变函数参数解析方式的语法,您必须显式创建生成器表达式:
It is easy to check if an element of a list is in another list using any()
:
any(elem in list2 for elem in list1)
but is there anyway to idiomatic way to return the first element found?
I'd prefer a one-line solution rather than:
for elem in list1:
if elem in list2:
return elem
This answer is similar to an answer on a similar question, where @jamylak goes into more detail of timing the results compared to other algorithms.
If you just want the first element that matches, use next
:
>>> a = [1, 2, 3, 4, 5]
>>> b = [14, 17, 9, 3, 8]
>>> next(element for element in a if element in b)
3
This isn't too efficient as it performs a linear search of b
for each element. You could create a set
from b
which has better lookup performance:
>>> b_set = set(b)
>>> next(element for element in a if element in b_set)
If next
doesn't find anything it raises an exception:
>>> a = [4, 5]
>>> next(element for element in a if element in b_set)
Traceback (most recent call last):
StopIteration
You can give it a default to return instead, e.g. None
. However this changes the syntax of how the function parameters are parsed and you have to explicitly create a generator expression:
>>> None is next((element for element in a if element in b_set), None)
True
这篇关于查找列表中的任何元素是否在另一个列表中并返回找到的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!