[英]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.