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))
发布于 2018-07-17 04:55:27
您使用是正确的,但是您需要遍历几个可能的长度才能产生最终输出。最后,我使用来扁平化结果列表:
>>> 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))
https://stackoverflow.com/questions/51369922
复制相似问题