-1

I know you can take the pairwise cross product of lists in the ways posted here: Pairwise crossproduct in Python

but I want to take a list L and a positive integer n and return the cross-product of L with itself n times. Is there a built in way to do this or will I just have to iterate the pairwise cross-product?

(or "cartesian product" for those who only use the sacred terminology handed down to them by their all-mighty high school math teacher...)

4

1 回答 1

3

您正在寻找itertools.product

输入迭代的笛卡尔积。

等效于生成器表达式中的嵌套 for 循环。例如,product(A, B) 返回与 ((x,y) for x in A for y in B) 相同的结果。

嵌套循环像里程表一样循环,每次迭代时最右边的元素都会前进。此模式创建一个字典顺序,以便如果输入的可迭代项已排序,则产品元组按排序顺序发出。

要计算可迭代对象与自身的乘积,请使用可选的 repeat 关键字参数指定重复次数。例如,product(A, repeat=4) 与 product(A, A, A, A) 的含义相同。

所以你只需要做

itertools.product(L, repeat=n)
于 2013-07-12T21:10:46.360 回答