返回Python列表中包含在另一个lis中的第一项

2024-09-30 23:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一个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的方式。你知道吗


Tags: 项目方法innone列表forreturnif
1条回答
网友
1楼 · 发布于 2024-09-30 23:35:08

可以使用生成器表达式和“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)时间复杂度操作)。你知道吗

相关问题 更多 >