首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >找出所有的组合,一次消除一个ar,直到list为空,在python 3中处理list的最佳数据结构是什么?

找出所有的组合,一次消除一个ar,直到list为空,在python 3中处理list的最佳数据结构是什么?
EN

Stack Overflow用户
提问于 2018-07-17 04:50:34
回答 1查看 30关注 0票数 -1
代码语言:javascript
复制
a = [1, 2, 3, 4]

组合包括:

代码语言:javascript
复制
[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]

代码:

代码语言:javascript
复制
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))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-17 04:55:27

您使用是正确的,但是您需要遍历几个可能的长度才能产生最终输出。最后,我使用来扁平化结果列表:

代码语言:javascript
复制
>>> 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

代码语言:javascript
复制
list(map(list, res))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51369922

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档