【发布时间】:2016-11-16 16:08:05
【问题描述】:
以下代码有效,但显得冗长。
def gen(l):
for x in range(l[0]):
for y in range(l[1]):
for z in range(l[2]):
yield [x, y, z]
l = [1, 2, 3]
print(list(gen(l)))
>>>[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2]]
我的意图是通过 itertools.product 减少 LOC。这就是我想出的。
from itertools import product
def gen(l):
for x, y, z in product(map(range, l)):
yield [x, y, z]
l = [1, 2, 3]
print(list(gen(l)))
ValueError: not enough values to unpack (expected 3, got 1)
是否有不同的方法来使用 itertools.product 以便有足够的值来解压?
【问题讨论】:
标签: python python-3.x generator itertools cartesian-product