itertools:排列的笛卡尔积 [英] itertools: Cartesian product of permutations

查看:95
本文介绍了itertools:排列的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using pythons itertools, I'd like to create an iterator over the outer product of all permutations of a bunch of lists. An explicit example:

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

虽然可行,但我想将其概括为任意列表列表.我试过了:

While this works, I'd like to generalize it to an arbitrary list of lists. I tried:

for x in itertools.product(map(itertools.permutations,[A,B,C])):
    print x

但是它没有达到我的预期.预期的输出是:

but it did not do what I intended. The expected output is:

((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个参数

You missed the * to unpack the list into 3 arguments

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

这篇关于itertools:排列的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆