在任意多个列表的python中交叉产品

cross product in python of arbitrarily many lists

我知道你可以通过这里发布的方式获取列表的成对交叉产品:python中的成对交叉产品

但是我想取一个列表l和一个正整数n,然后返回l的叉积和它本身的n次。是否有一种内置的方法来实现这一点,或者我只需要迭代成对的交叉积?

(或"笛卡尔产品",对于那些只使用他们所有强大的高中数学老师传给他们的神圣术语的人…)


你在找itertools.product

Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression. For example,
product(A, B) returns the same as ((x,y) for x in A for y in B).

The nested loops cycle like an odometer with the rightmost element
advancing on every iteration. This pattern creates a lexicographic
ordering so that if the input’s iterables are sorted, the product
tuples are emitted in sorted order.

To compute the product of an iterable with itself, specify the number
of repetitions with the optional repeat keyword argument. For example,
product(A, repeat=4) means the same as product(A, A, A, A).

所以你只需要做

1
itertools.product(L, repeat=n)