This question already has answers here:
Get the cartesian product of a series of lists?
(12个答案)
三年前关闭。
我是Python新手,我编写了一个函数:
def f(x, y, z):
    ret = []
    for i in range(x):
        for j in range(y):
            for k in range(z):
                ret.append((i, j, k))
    return ret


print f(2, 3, 4)

输出:
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]

但我对此并不满意,因为我认为必须缩短实现时间。
有人能给我点提示吗?

最佳答案

您可以使用itertools.product,因为这基本上就是您所追求的,Cartesian product

>>> from itertools import product
>>> list(product(range(2), range(3), range(4)))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]

因此,替换现有的功能就可以了。
def f(x, y, z):
    return list(product(range(x), range(y), range(z)))

若要删除必须键入range的次数,可以接受单个列表参数,然后使用生成器表达式,如
def f(l):
    return list(product(*(range(i) for i in l)))

所以你可以称之为
>>> f([2,3,4])
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]

关于python - Python:如何优雅地获得它? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34312220/

10-12 22:40
查看更多