[英]Create a list of sets of atoms
假設我有一個像這樣的原子數組:
['a', 'b', 'c']
(長度可以是任何)
我想創建一個可以用它們創建的集合列表:
[
['a'], ['b'], ['c'],
['a', 'b'], ['a', 'c'], ['b', 'c'],
['a', 'b', 'c']
]
是否可以在python中輕松完成?
也許這很容易做到,但我自己也沒有。
謝謝。
聽起來像powerset
:
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))
簡單。 使用itertools.combinations()
:
from itertools import combinations
atom = list('abc')
combs = [i for j in range(1, len(atom) + 1) for i in combinations(atom, j)]
產量:
[('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
你也可以這樣做:
from itertools import product
masks = [p for p in product([0, 1], repeat=len(data))]
combs = [[x for i, x in enumerate(data) if mask[i]] for mask in masks]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.