私はイテラブル オブジェクトのリストを持っており、各イテラブルから 0 または 1 項目で構成されるすべてのリストを取得することに関心があります (順序は重要ではないため、私が求める順列ではなく組み合わせです)。
以下に投稿した本当に洗練されていない実装があります。
おそらくモジュールを使用して、これを行うはるかにエレガントな方法があると確信していitertools
ますが、何も思いつきません。何かアドバイス?
import itertools
def all_subsets(ss):
subset_lens = range(0, len(ss) + 1)
list_of_subsets = map(lambda n: itertools.combinations(ss, n), subset_lens)
return itertools.chain.from_iterable(list_of_subsets)
list_of_iterables = [["A1"], ["B1", "B2", "B3"], ["C1", "C2"]]
all_possibilities = itertools.chain.from_iterable(itertools.product(*subset)
for subset in all_subsets(list_of_iterables))
# Visual representation of the desired result
for eg in all_possibilities:
print eg
結果:
()
('A1',)
('B1',)
('B2',)
('B3',)
('C1',)
('C2',)
('A1', 'B1')
('A1', 'B2')
('A1', 'B3')
('A1', 'C1')
...