本文介绍了在Python 3中使用itertools.product代替双嵌套的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码有效,但显示为冗长.

The following code works, but appears verbose.

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.这是我想出的.

My intention was to cut down on LOC with itertools.product. Here's what I came up with.

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,以便有足够的值可解压缩?

Is there a different way to use itertools.product so that there are enough values to unpack?

推荐答案

您需要使用*map迭代器的元素分别传递给product:

You need to pass the elements of the map iterator to product separately with *:

for x, y, z in product(*map(range, l))

偶然地,通过另一个map调用,您可以保存另一行,跳过Python生成器的开销,并在C中完成所有工作:

Incidentally, with another map call, you could save another line, skip the overhead of a Python generator, and do all the work in C:

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

这篇关于在Python 3中使用itertools.product代替双嵌套的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:33