【发布时间】:2018-10-15 23:16:39
【问题描述】:
考虑以下函数:
它将列表列表作为输入,并从每个列表中查找元素的所有组合。
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 函数中的嵌套列表理解吗?
【问题讨论】:
标签: python python-3.x list list-comprehension nested-loops