有没有一个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'
但是我想知道是否有一种更优雅、更有效、更像Python的方式。你知道吗
可以使用生成器表达式和“next()”函数。示例-
如果“list2”中不存在满足条件的项,则也将返回
None
。你知道吗在上面的函数中,我首先将列表'list2'转换为
set
,以便在固定时间内进行搜索(否则在list
中搜索是一个O(n)时间复杂度操作)。你知道吗相关问题 更多 >
编程相关推荐