创建原子集合的列表

2024-04-26 17:48:53 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个这样的原子阵列:

['a', 'b', 'c']

(长度可以是任意的)

我想创建一个可以用它们制作的集合的列表:

^{pr2}$

有没有可能在python中很容易地做到这一点?在

也许这很容易做到,但我自己却不懂。
非常感谢。在


Tags: 列表原子pr2
3条回答

别紧张。使用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)]

结果是:

^{pr2}$

听起来像^{}

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))

您还可以执行以下操作:

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]

相关问题 更多 >