Python: 计算列表的笛卡尔幂的最简方法
假设我们有一个列表 L
。我们可以这样计算这个列表的笛卡尔积 L x L
:
product = [(a,b) for a in L for b in L]
那么,如何以简短而高效的方式计算笛卡尔幂 L x L x L x ... x L
(重复 n 次,对于给定的 n)呢?
1 个回答
10
product = itertools.product(L, repeat=n)
这里的 product
现在是一个可迭代的对象;如果你想把它变成一个完整的列表,可以调用 list(product)
:
>>> from itertools import product
>>> list(product(range(3), repeat=2))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]