input set [1,2,3]
使用itertools.combinations,我们可以使用此程序获得以下输出
>>> a = []
>>> x = [1,2,3]
>>> for t in range(1, len(x)+1):
... k = itertools.combinations(x,t)
... a.append([y for y in k])
我得到以下输出
[ [(1), (2), (3)], [(1, 2), (1, 3), (2, 3)], [(1, 2, 3)] ]
但我正在寻找这个输出:
[ [(1), (1, 2), (1, 2, 3), (1, 3)], [(2), (2, 3)], [(3)] ]
任何想要获得此输出的人。
答案 0 :(得分:4)
这是一个解决方案,按照所需顺序生成组合元组的展平列表(如您所说,在评论中可接受):
def combos(x):
if len(x) == 0:
return []
cs = combos(x[1:])
return [(x[0],)] + [(x[0],) + c for c in cs] + cs
如果您将其调用为:
print(combos([1, 2, 3]))
结果是:
[(1,), (1, 2), (1, 2, 3), (1, 3), (2,), (2, 3), (3,)]
同样,这是展平列表,但元组按您请求的顺序排列。
答案 1 :(得分:1)
你可以对它进行压扁和排序:
sorted(sum(a, []))
演示:
>>> a = [[(1,), (2,), (3,)], [(1, 2), (1, 3), (2, 3)], [(1, 2, 3)]]
>>> sorted(sum(a, []))
[(1,), (1, 2), (1, 2, 3), (1, 3), (2,), (2, 3), (3,)]