Python itertools 不确定维度的乘积

Python itertools product of undefinite dimension

我想生成 N 个变量的笛卡尔积,N 本身就是一个变量。假设 table 是一个列表,我怎样才能得到所有 i 的 [0, table[i] - 1] 的笛卡尔积?
如果我知道 table 的长度总是 3,我会写 itertools.product(xrange(table[0]), xrange(table[1]), xrange(table[2]))。但是如何使用未定义的 table 长度来做到这一点?
感谢您的帮助。

您想使用 Python 的 "splat" 运算符 func(*iterable)

>>> import itertools
>>> table = [1, 5, 3]
>>> iterator = itertools.product(*map(xrange, table))
>>> list(iterator)
[(0, 0, 0), (0, 0, 1), (0, 0, 2),
(0, 1, 0), (0, 1, 1), (0, 1, 2),
(0, 2, 0), (0, 2, 1), (0, 2, 2),
(0, 3, 0), (0, 3, 1), (0, 3, 2),
(0, 4, 0), (0, 4, 1), (0, 4, 2)]

一种方法是使用列表理解:

itertools.product(*[xrange(t) for t in table])