考虑以下函数:
它将列表列表作为输入,并从每个列表中查找元素的所有组合。
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/