2024-04-26 17:48:53 发布
网友
假设我有一个这样的原子阵列:
['a', 'b', 'c']
(长度可以是任意的)
我想创建一个可以用它们制作的集合的列表:
有没有可能在python中很容易地做到这一点?在
也许这很容易做到,但我自己却不懂。 非常感谢。在
别紧张。使用itertools.combinations():
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)]
结果是:
听起来像^{}:
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]
别紧张。使用
itertools.combinations()
:结果是:
^{pr2}$听起来像^{} :
您还可以执行以下操作:
相关问题 更多 >
编程相关推荐