gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:15:31 28 4
gpt4 key购买 nike

考虑以下函数:

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

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com