【发布时间】:2017-07-25 15:55:35
【问题描述】:
是否有任何 pythonic 方法来生成多个列表之间的组合? (类似于笛卡尔积但更复杂)
例子:
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
# ...
# there are more than 3 lists
预期输出:
1. [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
2. [(1, 4, 8), (2, 5, 7), (3, 6, 9)]
3. [(1, 4, 9), (2, 5, 7), (3, 6, 8)]
4. [(1, 5, 7), (2, 4, 8), (3, 6, 9)]
5. ...
更新:
感谢您的快速回复~!!
澄清问题:
结果是列表a、b、c的笛卡尔积的所有非重复组合。
可以通过另一种丑陋的方法来完成:
1) 生成笛卡尔积的整个列表
from itertools import product, combinations, chain
t = list(product(a, b, c))
2) 使用组合产生所有可能的结果
p = list(combinations(t, 3))
3) 过滤重复条件
cnt = len(list(chain(a, b, c)))
f = [x for x in p if len(set(chain(*x))) == cnt]
更新2:
丑陋的方法产生的预期结果:
((1, 4, 7), (2, 5, 8), (3, 6, 9))
((1, 4, 7), (2, 5, 9), (3, 6, 8))
((1, 4, 7), (2, 6, 8), (3, 5, 9))
((1, 4, 7), (2, 6, 9), (3, 5, 8))
((1, 4, 8), (2, 5, 7), (3, 6, 9))
((1, 4, 8), (2, 5, 9), (3, 6, 7))
((1, 4, 8), (2, 6, 7), (3, 5, 9))
((1, 4, 8), (2, 6, 9), (3, 5, 7))
((1, 4, 9), (2, 5, 7), (3, 6, 8))
((1, 4, 9), (2, 5, 8), (3, 6, 7))
((1, 4, 9), (2, 6, 7), (3, 5, 8))
((1, 4, 9), (2, 6, 8), (3, 5, 7))
((1, 5, 7), (2, 4, 8), (3, 6, 9))
((1, 5, 7), (2, 4, 9), (3, 6, 8))
((1, 5, 7), (2, 6, 8), (3, 4, 9))
((1, 5, 7), (2, 6, 9), (3, 4, 8))
((1, 5, 8), (2, 4, 7), (3, 6, 9))
((1, 5, 8), (2, 4, 9), (3, 6, 7))
((1, 5, 8), (2, 6, 7), (3, 4, 9))
((1, 5, 8), (2, 6, 9), (3, 4, 7))
((1, 5, 9), (2, 4, 7), (3, 6, 8))
((1, 5, 9), (2, 4, 8), (3, 6, 7))
((1, 5, 9), (2, 6, 7), (3, 4, 8))
((1, 5, 9), (2, 6, 8), (3, 4, 7))
((1, 6, 7), (2, 4, 8), (3, 5, 9))
((1, 6, 7), (2, 4, 9), (3, 5, 8))
((1, 6, 7), (2, 5, 8), (3, 4, 9))
((1, 6, 7), (2, 5, 9), (3, 4, 8))
((1, 6, 8), (2, 4, 7), (3, 5, 9))
((1, 6, 8), (2, 4, 9), (3, 5, 7))
((1, 6, 8), (2, 5, 7), (3, 4, 9))
((1, 6, 8), (2, 5, 9), (3, 4, 7))
((1, 6, 9), (2, 4, 7), (3, 5, 8))
((1, 6, 9), (2, 4, 8), (3, 5, 7))
((1, 6, 9), (2, 5, 7), (3, 4, 8))
((1, 6, 9), (2, 5, 8), (3, 4, 7))
【问题讨论】:
-
你想要一个迭代器吗?那么
itertools.product(*args)就是你要找的东西。只需将您的列表设置为arg。 -
@MarvinTaschenberger:你试过吗?
-
为什么没有
[(1, 4, 8), (2, 5, 9), (3, 6, 7)]? -
您的问题并不完全清楚。您希望该输入数据有多少行输出?如果您想要 a、b 和 c 的每个排列的笛卡尔积,则需要 216 行。
-
我已经为@PM2Ring 的建议编写了代码。如果是这种情况,请改写问题。
标签: python algorithm combinations itertools