Python: 计算列表的笛卡尔幂的最简方法

7 投票
1 回答
1703 浏览
提问于 2025-04-17 14:15

假设我们有一个列表 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

使用 itertools.product()

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)]

撰写回答