【发布时间】:2015-10-16 12:55:54
【问题描述】:
是否有一种 Pythonic 方式来返回列表中的第一个项目,该项目也是另一个列表中的项目?目前我正在使用蛮力和无知来做这件事:
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' 但我想知道是否有更优雅/高效/Pythonic 的方式。
【问题讨论】:
-
我不确定 Python 集是否可能是这里的方法,但我需要将列表 A 中的第一个项目与列表 B 中的任何项目匹配,并且我相信 Python 集是无序的?
-
这似乎很好,虽然你不需要明确地
return None。如果元素是可散列的(如您的字符串),您可以将b设置为更有效的集合。 -
>>> 的技术术语是什么?我在文档中找不到它。
-
next(item for item in a if item in b) -
@TimGJ 你错过了第一个
item...
标签: python