首页 > 解决方案 > 查找所有组合,通过消除一个 ar 直到列表为空,以及在 python 3 中处理列表的最佳数据结构是什么?

问题描述

a = [1, 2, 3, 4]

组合是:

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

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

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

代码:

from itertools import combinations

a = [1, 2, 3, 4]

list1 = list()

b = combinations(a, len(a)-1)

for i in b:

    list1.append(list(i))

list2 = list()


while len(list1) != 0:

    temp = list1.pop()

    comb = combinations(temp, len(temp)-1)

    for i in comb:

        if list(i) not in list2:

            print(list(i))

            list2.append(list(i))

标签: pythonpython-3.xlistdata-structures

解决方案


您使用 是正确的itertools.combinations,但是您需要遍历几个可能的长度才能产生最终输出。最后,我曾经itertools.chain.from_iterable将结果列表展平:

>>> from itertools import chain, combinations
>>> list(chain.from_iterable(combinations(a, i) for i in range(1, len(a))))
[(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)]

如果您对列表中的元素一无所知,请存储结果并使用map

list(map(list, res))

推荐阅读