【问题标题】:itertools: Cartesian product of permutationsitertools:排列的笛卡尔积
【发布时间】:2012-08-17 09:13:06
【问题描述】:

使用 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))

【问题讨论】:

    标签: python permutation itertools cartesian-product


    【解决方案1】:

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

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

    【讨论】:

    • 这解决了上述问题 - 但它具有将排列扩展到完整列表的不幸副作用,完全破坏了迭代器的意图。当其中一个列表甚至是中等大小(例如 13)时,N! 存储在内存中时会变成一个巨大的数字。
    • @Hooked 不!它将在 3 个参数中使用 3 个迭代器扩展列表(仍然是迭代器)
    • A=range(13)BC 相同。当然,这个迭代器中有 13!**3 个元素,但我们应该能够遍历它们(这就是迭代器的全部意义,对吧?)。内存使用量在列出一个之前就爆炸了。试试看 - 效果不一样吗?
    • @Hooked 它也会在您的原始版本中发生。这是一些与product 相关的问题...我稍后会尝试检查(但两个代码的运行方式相同)
    • @Hooked 现在我记得了!这很简单:product 之前需要将迭代器转换为列表,因为它们需要循环多次(并且迭代器只能使用一次)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2019-07-23
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多