【问题标题】:Returning the first item in a Python list which is contained in another list返回包含在另一个列表中的 Python 列表中的第一项
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 甜蜜。我永远不会想到使用下一个。我想这就是 stackoverflow 如此有用的原因。
  • 我认为将其转换为 next 之前的集合并没有特别的优势 - 即它与 return next((item for item in a if item in set(b)), None) 一样有效
  • 使用您的版本,每次我们检查该条件时,它都会将整个 b 列表转换为 set ,如果您在 next 之前将其转换为 set ,它只会转换为 set 一次。
  • 代码会更清晰,如果你可以使用像'list1','list2'这样的变量名,OP也一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多