python – 一个列表中的两个组合列表

我是一个Python初学者.我想从一个列表中获取两个组合列表.

例如,我有一个列表:

c = [1, 2, 3, 4]

我想使用每四个项目来获得每个可能的组合来填充两个列表.将会有((2 ^ 4)/ 2)-1种可能性.

c1 = [1]  c2 = [2, 3, 4]
c1 = [2]  c2 = [1, 3, 4]
c1 = [3]  c2 = [2, 3, 4]
c1 = [4]  c2 = [1, 2, 3]
c1 = [1, 2]  c2 = [3, 4]
c1 = [1, 3]  c2 = [2, 4]
c1 = [1, 4]  c2 = [2, 3]

这个函数通常适用于itertools,但我不能选择itertools.combination生成的列表数.

该功能只允许我选择每个列表应该有多少项.

例如,如果我尝试以下功能,

print list(itertools.combinations(c, 2))

我只能这样得到一个结果.

[(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]

我很难找到这个,但我找不到任何东西.

更新

哦,我可怜的英语造成了这样的混乱!我完全改变了我的榜样.我想将4个项目分配到2个列表.对困惑感到抱歉!

解决方法:

我不确定你对10选择2的理解是什么.您从列表中收到的输出(itertools.combinations(c,2))是数学定义为10C2的输出.

编辑

从编辑到您的问题,您似乎想要一种完全不同的组合.结果的数量仍然不是45,而是:10C1 10C2 10C3 10C4 10C5.

我希望以下内容可以帮助您前进:

for i in range(1, 6):
    for c1 in itertools.combinations(c, i):
            c1 = set(c1)
            c2 = set(c) - c1
            print c1, c2

上述代码的灵感来自this (deleted) answerCSZ.

使用范围(1,3)时收到的输出:

[1] [2, 3, 4, 5, 6, 7, 8, 9, 10]
[2] [1, 3, 4, 5, 6, 7, 8, 9, 10]
[3] [1, 2, 4, 5, 6, 7, 8, 9, 10]
[4] [1, 2, 3, 5, 6, 7, 8, 9, 10]
[5] [1, 2, 3, 4, 6, 7, 8, 9, 10]
[6] [1, 2, 3, 4, 5, 7, 8, 9, 10]
[7] [1, 2, 3, 4, 5, 6, 8, 9, 10]
[8] [1, 2, 3, 4, 5, 6, 7, 9, 10]
[9] [1, 2, 3, 4, 5, 6, 7, 8, 10]
[10] [1, 2, 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, 3, 4, 6, 7, 9, 10]
[9, 5] [1, 2, 3, 4, 6, 7, 8, 10]
[10, 5] [1, 2, 3, 4, 6, 7, 8, 9]
[6, 7] [1, 2, 3, 4, 5, 8, 9, 10]
[8, 6] [1, 2, 3, 4, 5, 7, 9, 10]
[9, 6] [1, 2, 3, 4, 5, 7, 8, 10]
[10, 6] [1, 2, 3, 4, 5, 7, 8, 9]
[8, 7] [1, 2, 3, 4, 5, 6, 9, 10]
[9, 7] [1, 2, 3, 4, 5, 6, 8, 10]
[10, 7] [1, 2, 3, 4, 5, 6, 8, 9]
[8, 9] [1, 2, 3, 4, 5, 6, 7, 10]
[8, 10] [1, 2, 3, 4, 5, 6, 7, 9]
[9, 10] [1, 2, 3, 4, 5, 6, 7, 8]
上一篇:C++ 练习题


下一篇:python pandas,一个函数将根据另一行的条件应用于一行中元素的组合