のような出力たい:リスト内包と組み合わせ
>>> import itertools
>>> xs = [1, 2, 3]
>>> itertools.combinations(xs, 2) # returns an iterator
<itertools.combinations object at 0x7f88f838ff48>
>>> list(itertools.combinations(xs, 2)) # yields 2-length subsequences
[(1, 2), (1, 3), (2, 3)]
>>> for i in range(0, len(xs) + 1): # to get all lengths: 0 to 3
... for subset in itertools.combinations(xs, i):
... print(list(subset))
...
[]
[1]
[2]
[3]
[1, 2]
[1, 3]
[2, 3]
[1, 2, 3]
を、あなたが望む結果を得るでしょう:
>>> [list(subset) for i in range(0, len(xs) + 1)
for subset in itertools.combinations(xs, i)]
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
組み合わせを使用しない場合は、他の方法があります –
@RISHABHBANSAL、私が知る限り、 'itertools.com最も簡単です。これがなければ、再帰関数を作成する必要があります。 – falsetru