在Python

时间:2017-06-23 21:32:12

标签: python list combinations

我在python中有一个list

[1,2,3,4]

我想生成此list的所有可能拆分:

[1,2,3,4]
[1] [2,3,4]
[2] [1,3,4]
[3] [1,2,4]
[4] [1,2,3]
[1,2] [3,4]
[1,3] [2,4]
[1,4] [2,3]

最好的方法是什么?我可以使用itertools.combinations()生成第一面,但考虑到listsubset,最简单的计算余数的方法是什么?

4 个答案:

答案 0 :(得分:2)

from itertools import combinations, chain
x = [1, 2, 3, 4]
subsets = [v for a in range(len(x)) for v in combinations(x, a)]
for i in range(len(subsets)/2 + 1):
    print list(chain(subsets[i])), ' ', [e for e in x if e not in subsets[i]]

输出:

[]   [1, 2, 3, 4]
[1]   [2, 3, 4]
[2]   [1, 3, 4]
[3]   [1, 2, 4]
[4]   [1, 2, 3]
[1, 2]   [3, 4]
[1, 3]   [2, 4]
[1, 4]   [2, 3]

答案 1 :(得分:1)

您可以使用list-comprehension获取剩余部分:

[x for x in a if x not in b]

假设a是原始listbsubset

修改

如果你想避免重复,可以在打印前创建一个要检查的列表,同时检查空余数(完整列表):

a = [1, 2, 3, 4]
b = [list(c) for i in xrange(len(a)) for c in itertools.combinations(a, i+1)]
check = []
for elem in b:
    remainder = [x for x in a if x not in elem]
    if remainder not in check and remainder:
        print '{} {}'.format(elem, remainder)
        check.append(elem)

输出:

[1] [2, 3, 4]
[2] [1, 3, 4]
[3] [1, 2, 4]
[4] [1, 2, 3]
[1, 2] [3, 4]
[1, 3] [2, 4]
[1, 4] [2, 3]

答案 2 :(得分:0)

另一种方法是将它们变成集合并做一个简单的集合差异。

full = [1, 2, 3, 4]
full_set = set(full)
for partition in itertools.combinations(...):
    remainder = list(full_set - set(partition))
    print partition, remainder

答案 3 :(得分:0)

这个怎么样?

>>> import itertools
>>> x = [1,2,3,4]
>>> for i in range(len(x)):
...     for c in [c for c in itertools.combinations(x, i+1)]:
...             print(list(c), [i for i in x if not i in c])
...
[1] [2, 3, 4]
[2] [1, 3, 4]
[3] [1, 2, 4]
[4] [1, 2, 3]
[1, 2] [3, 4]
[1, 3] [2, 4]
[1, 4] [2, 3]
[2, 3] [1, 4]
[2, 4] [1, 3]
[3, 4] [1, 2]
[1, 2, 3] [4]
[1, 2, 4] [3]
[1, 3, 4] [2]
[2, 3, 4] [1]
[1, 2, 3, 4] []