Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回Python列表中包含在另一个列表中的第一项_Python - Fatal编程技术网

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

返回Python列表中包含在另一个列表中的第一项,python,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

是否有一种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'
但我想知道是否有一种更优雅/高效/Pythonic的方法。

可以使用生成器表达式和'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)
如果“列表2”中不存在符合条件的项目,则此操作也将返回
None


在上面的函数中,我首先将列表'list2'转换为一个
集合
,这样就可以在固定的时间内进行搜索(否则在
列表
中搜索是一个O(n)时间复杂度操作)。

我不确定Python集合是否是实现此目的的方法,但我需要将列表a中的第一项与列表B中的任何项匹配,我相信Python集是无序的?这看起来不错,尽管您不需要显式地
返回None
。如果元素是可散列的(比如字符串),您可以将
b
设置为更高效的一组?我在文档中找不到它。
下一步(a中的项目对应b中的项目)
@TimGJ您缺少第一个
项目
…甜蜜。我从来没有想过使用next。我想这就是stackoverflow如此有用的原因。我认为在
next
之前将其转换为一个集合没有什么特别的好处,也就是说,将其转换为
return next(在集合(b)中的if item中的item for item,None)同样有效
在您的版本中,每次我们检查该条件时,它都会将整个b列表转换为set,如果您在下一步之前将其转换为set,它只会转换为set一次。如果您可以使用变量名,如'list1','list2',则代码会更清晰,OP也可以使用相同的变量名。