python - 查找所有组合,通过消除一个 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))
解决方案
您使用 是正确的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))
推荐阅读
- android - Android错误:无法解决::未指定:受影响的模块:app
- python - Python For Loop 经常执行
- typescript - 为什么在打字稿中扩展类时没有类型提示
- python - 使用 openCV 和 Python 将对象从一个图像映射到另一个图像
- python - 在 nbconvert 中导出为 PDF 时格式化表格
- mongodb - 使用 MongoDB 驱动程序删除多个文档不起作用
- javascript - 盒子阴影切断
- genetic-algorithm - 俄罗斯方块算法的最佳策略是什么?
- javascript - 未捕获的 SyntaxError:标识符“按钮”已被声明
- ubuntu - Nginx 只替换根域(保留子域)