[英]Returning the first item in a Python list which is contained in another list
Is there a Pythonic way of returning the first item in a list which is also an item in another list? 是否有Pythonic方式返回列表中的第一个项目,这也是另一个列表中的项目? At the moment I'm doing it using brute force and ignorance:
目前我正在使用蛮力和无知来做这件事:
def FindFirstMatch(a, b):
"""
Returns the first element in a for which there is a matching
element in b or None if there is no match
"""
for item in a:
if item in b:
return item
return None
So FindFirstMatch(['Fred','Wilma','Barney','Betty'], ['Dino', 'Pebbles', 'Wilma', 'Bambam'])
returns 'Wilma'
but I wondered if there was a more elegant/efficient/Pythonic way. 因此,
FindFirstMatch(['Fred','Wilma','Barney','Betty'], ['Dino', 'Pebbles', 'Wilma', 'Bambam'])
返回'Wilma'
但我想知道是否有更优雅/高效/ Pythonic方式。
You can use a generator expression and 'next()' function . 您可以使用生成器表达式和'next()'函数。 Example -
示例 -
def FindFirstMatch(list1, list2):
"""
Returns the first element in list "list1" for which there is a matching
element in list "list2" or None if there is no match
"""
setb = set(list2)
return next((item for item in list1 if item in setb),None)
This would also return None
if no such item meeting the condition exist in 'list2' . 如果'list2'中不存在满足条件的此类项,则也将返回
None
。
In the above function, I am first converting list 'list2' into a set
, so that searching in it can be done in constant time (otherwise searching in list
is an O(n) time complexity operation). 在上面的函数中,我首先将列表'list2'转换为
set
,以便在其中进行搜索可以在恒定时间内完成(否则在list
搜索是O(n)时间复杂度操作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.