如何在Python中扩展此嵌套列表理解

悉达多(Siddharth vashishtha)

考虑以下功能:

它以列表列表作为输入,并从每个列表中查找元素的所有组合。

def product(llist):
    result = [[]]

    for lst in llist:
        result = [x + [y] for x in result for y in lst]

    return result

例如:

product([[1,2], [3], [4,5]])

会返回:

[[1, 3, 4], [1, 3, 5], [2, 3, 4], [2, 3, 5]]

我试图了解此功能的工作原理,因此试图扩大列表的理解范围。

尝试一下:

def product2(llist):
    result = [[]]
    for lst in llist:
        for x in result:
            result = []
            for y in lst:
                result.append(x+[y])

    return result

这没有给我正确的结果,它返回:

[[2, 3, 4], [2, 3, 5]]

并且根据的定义,我理解了这种错误的结果product2但是我无法扩展原始product功能以了解其工作方式。

有人可以详细说明product函数中的嵌套列表理解吗?

滑杆

列表理解是为中的每个元素创建一个新列表lst,并通过将这个小的单个元素列表与已经存在的所有列表组合来创建新的列表result

因此,例如ifresult = [ [1, 2], [3, 4] ]lst = [10, 11],新结果将是[[1, 2, 10], [1, 2, 11], [3, 4, 10], [3, 4, 11]]

它在每个lst中都这样做llist

def product2(llist):
    result = [[]]
    for lst in llist:
        new_result = [] # let's manually build out new result
        for existing in result:            
            for element in lst:
                new_result.append(existing + [element])
        result = new_result # update result for next lst
    return result

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章