python - 如何在 Python 中扩展这个嵌套列表理解

标签 python python-3.x list list-comprehension nested-loops

考虑以下函数:

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

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 中已有的所有列表组合来创建更多新列表。 。

例如,如果 result = [ [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

关于python - 如何在 Python 中扩展这个嵌套列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52825941/

相关文章:

python - 如何强制 Django 模型中的 2 个字段共享相同的默认值?

python - 在循环中调用 repaint() 时,pyqt5 中的 QPainter 不会绘制任何内容。我该如何解决?

r - append 到 R 中的列表会导致复制吗?

python - 如何展平 2 深列表,返回其中不包含任何子列表的列表

带有 call_later 的 Python asyncio 递归

python - Pandas:创建一个将一列与其他两列相关的数据框

list - 如何使用递归删除 Racket 列表中的第一个和最后一个元素

django - 如何将 Django 2.0 url() 转换为 path()

python - 如何计算字符串开头的字符数?

python - 重命名python列表中的项目