Python中列表的可能组合

时间:2014-11-19 05:02:15

标签: python

给出一个清单: 例如:[1,2,3,4]。

打印以下内容: [],[1],[1,2],[1,2,3],[1,2,3,4],[2],[2,3],[2,3,4]等上

基本上我们需要获得所有组合。

3 个答案:

答案 0 :(得分:1)

使用itertools.combinations

>>> import itertools
>>> my_list = [1,2,3,4]
>>> [ list(x) for i in range(len(my_list)+1) for x in itertools.combinations(my_list,i) ]
[[], [1], [2], [3], [4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]]

如果你想连续:

>>> [[]]+[ my_list[i:j] for i in range(len(my_list)) for j in range(i+1,len(my_list)+1) ]
[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]

答案 1 :(得分:0)

这篇文章解释了如何: How to get all possible combinations of a list’s elements?

[[x for x in itertools.combinations([1,2,3,4], y)] for y in range(4)]

这将提供答案。 itertools.combinations([1,2,3,4], y)将提供y元素的所有组合。 range(4)将提供1到4的范围 嵌套列表推导迭代了要组合的元素数量和组合本身。

输出结果为:

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

然后我们可以使用chain.from_iterable展开列表,如本文所述:Making a flat list out of list of lists in Python

list(itertools.chain.from_iterable([[x for x in itertools.combinations([1,2,3,4], y)] for y in range(4)]))

最终输出:

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

答案 2 :(得分:0)

如果您的输入值始终是连续的,您可以尝试以下想法:

result = []

for i in xrange(1, 6):
    for j in xrange(1, 6):
        if i > j:
            result.append(range(j, i))

print [[]] + sorted(result)

结果:

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