Python itertools:置换的笛卡尔积

Python itertools:置换的笛卡尔积,python,permutation,itertools,cartesian-product,Python,Permutation,Itertools,Cartesian Product,使用pythonsitertools,我想在一组列表的所有排列的外积上创建一个迭代器。一个明确的例子: import itertools A = [1,2,3] B = [4,5] C = [6,7] for x in itertools.product(itertools.permutations(A),itertools.permutations(B),itertools.permutations(C)): print x 虽然这样做有效,但我想将其推广到任意列表。我试过: fo

使用pythons
itertools
,我想在一组列表的所有排列的外积上创建一个迭代器。一个明确的例子:

import itertools
A = [1,2,3]
B = [4,5]
C = [6,7]

for x in itertools.product(itertools.permutations(A),itertools.permutations(B),itertools.permutations(C)):
    print x
虽然这样做有效,但我想将其推广到任意列表。我试过:

for x in itertools.product(map(itertools.permutations,[A,B,C])):
    print x
但它没有达到我的目的。预期产出为:

((1, 2, 3), (4, 5), (6, 7))
((1, 2, 3), (4, 5), (7, 6))
((1, 2, 3), (5, 4), (6, 7))
((1, 2, 3), (5, 4), (7, 6))
((1, 3, 2), (4, 5), (6, 7))
((1, 3, 2), (4, 5), (7, 6))
((1, 3, 2), (5, 4), (6, 7))
((1, 3, 2), (5, 4), (7, 6))
((2, 1, 3), (4, 5), (6, 7))
((2, 1, 3), (4, 5), (7, 6))
((2, 1, 3), (5, 4), (6, 7))
((2, 1, 3), (5, 4), (7, 6))
((2, 3, 1), (4, 5), (6, 7))
((2, 3, 1), (4, 5), (7, 6))
((2, 3, 1), (5, 4), (6, 7))
((2, 3, 1), (5, 4), (7, 6))
((3, 1, 2), (4, 5), (6, 7))
((3, 1, 2), (4, 5), (7, 6))
((3, 1, 2), (5, 4), (6, 7))
((3, 1, 2), (5, 4), (7, 6))
((3, 2, 1), (4, 5), (6, 7))
((3, 2, 1), (4, 5), (7, 6))
((3, 2, 1), (5, 4), (6, 7))
((3, 2, 1), (5, 4), (7, 6))

您错过了将列表解压为3个参数的
*

itertools.product(*map(itertools.permutations,[A,B,C]))

这解决了前面提到的问题——但它有一个不幸的副作用,那就是将排列扩展到完整的列表中,完全破坏了迭代器的意图。当其中一个列表甚至是中等大小时,比如说13,
N存储在内存中时会变成一个巨大的数字。@Hooked No!它将用3个参数中的3个迭代器(仍然是迭代器)展开列表,让
A=range(13)
,对于
B
C
也是如此。当然有13个**这个迭代器中有3个元素,但我们应该能够遍历它们(这就是迭代器的全部要点,对吗?)。在列出单个内存之前,内存使用量就会增加。试试看-你没有同样的效果吗?@Hooked它也会出现在你的原始版本中。这是一些与产品相关的问题。。。我稍后会尝试检查(但两个代码都以相同的方式运行)@Hooked现在我记得了!这很简单:
product
之前需要将迭代器转换为列表,因为它们需要循环多次(迭代器只能使用一次)