返回包含在另一个列表中的Python列表中的第一个项目
问题描述:
返回列表中的第一个项目是否也是另一个列表中的项目?目前我使用蛮力和无知做:返回包含在另一个列表中的Python列表中的第一个项目
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
所以FindFirstMatch(['Fred','Wilma','Barney','Betty'], ['Dino', 'Pebbles', 'Wilma', 'Bambam'])
回报'Wilma'
但我想知道是否有一个更优雅/有效的/ Python的方式。
答
您可以使用生成器表达式和'next()'函数。示例 -
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)
如果'list2'中不存在满足条件的此类项目,这也将返回None
。
在上述函数中,我首先将列表'list2'转换为set
,以便可以在恒定时间内完成搜索(否则在list
中搜索是O(n)时间复杂度操作)。
我不确定Python集合是否可以成为这里的途径,但是我需要将列表A中的第一项与列表B中的任何项匹配,并且我相信Python集合是无序的? – TimGJ
看起来不错,虽然你不需要明确地返回None。如果元素是可散列的(比如你的字符串),你可以使'b'集合更高效。 – jonrsharpe
>>>的术语是什么?我无法在文档中找到它。 – ergonaut