在Python 3中使用itertools.product代替双嵌套for循环

在Python 3中使用itertools.product代替双嵌套for循环,python,python-3.x,generator,itertools,cartesian-product,Python,Python 3.x,Generator,Itertools,Cartesian Product,下面的代码可以工作,但看起来很冗长 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,

下面的代码可以工作,但看起来很冗长

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,以便有足够的值进行解包

您需要使用
*
分别将
映射
迭代器的元素传递到
产品

for x, y, z in product(*map(range, l))
顺便说一句,通过另一个
map
调用,您可以节省另一行代码,跳过Python生成器的开销,并用C完成所有工作:

def gen(l):
    return map(list, product(*map(range, l)))

使用星号分隔元素效果很好,但答案的第二部分返回TypeError:“int”对象不可编辑。@CannedSpinach:不应该发生这种情况。我确实错过了它返回元组迭代器而不是列表(您可以通过另一个
map
调用来实现),甚至是元组版本。