查找列表中的任何元素是否在另一个列表中并返回找到的第一个元素 [英] Finding if any element in a list is in another list and return the first element found

查看:49
本文介绍了查找列表中的任何元素是否在另一个列表中并返回找到的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用any()很容易检查一个列表的元素是否在另一个列表中:

any(elem in list2 for elem in list1)

但是无论如何都有返回找到的第一个元素的惯用方法吗?

我更喜欢单行解决方案而不是:

对于列表 1 中的元素:如果列表 2 中的元素:返回元素

解决方案

这个答案类似于 关于类似问题的答案,与其他算法相比,@jamylak 更详细地介绍了结果计时.

如果您只想要匹配的第一个元素,请使用 下一步:

<预><代码>>>>a = [1, 2, 3, 4, 5]>>>b = [14, 17, 9, 3, 8]>>>下一个(b 中的 if 元素中的元素的元素)3

这不是太有效,因为它对每个元素执行 b 的线性搜索.您可以从 b 创建一个 set ,它具有更好的查找性能:

<预><代码>>>>b_set = 设置(b)>>>next(b_set 中的 if 元素中的元素的元素)

如果 next 没有找到任何东西,它会引发异常:

<预><代码>>>>a = [4, 5]>>>next(b_set 中的 if 元素中的元素的元素)回溯(最近一次调用最后一次):停止迭代

你可以给它一个默认的返回值,例如.但是,这会改变函数参数解析方式的语法,您必须显式创建生成器表达式:

<预><代码>>>>无是下一个((b_set 中的 if 元素中的元素的元素),无)真的

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆