我想实现一个在数组中循环的代码,其大小由用户设置,这意味着大小不是常量。
例如: A = [1,2,3,4,5] 那么我希望输出是这样的:
[1],[2],[3],[4],[5]
[1,2],[1,3],[1,4],[1,5]
[2,3],[2,4],[2,5]
[3,4],[3,5]
[4,5]
[1,2,3],[1,2,4],[1,2,5]
[1,3,4],[1,3,5]
and so on
[1,2,3,4],[1,2,3,5]
[2,3,4,5]
[1,2,3,4,5]
你能帮我实现这段代码吗?
答案 0 :(得分:3)
来自itertools
documentation:
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
如果您不想要空集,则很容易删除。
(我假设你的例子中的换行没有意义。如果有,请解释如何。)
答案 1 :(得分:1)
示例:
>>> from itertools import combinations
>>> A = [1,2,3,4,5]
>>> for i in xrange(1, len(A)+1):
... for c in combinations(A, i):
... print c
...
(1,)
(2,)
(3,)
(4,)
(5,)
(1, 2)
(1, 3)
(1, 4)
(1, 5)
(2, 3)
(2, 4)
...
...
(2, 4, 5)
(3, 4, 5)
(1, 2, 3, 4)
(1, 2, 3, 5)
(1, 2, 4, 5)
(1, 3, 4, 5)
(2, 3, 4, 5)
(1, 2, 3, 4, 5)