Python:列表中所有可能的子集组合

时间:2020-05-16 09:36:26

标签: python algorithm combinations itertools

我有一个列表:

list = ["M","M","M","C","C","C"]

我希望输出为

out = [["M"],["C"],["M,"C"],["M","M"],["C","C"]]

该怎么做?预先感谢!

我使用了以下代码:

from itertools import chain, combinations
stuff = ["M","M","M","C","C","C"]
def all_subsets(ss):
    p = map(lambda x: combinations(ss, x), range(1, 3))
    return p

for subset in all_subsets(stuff):
    print(list(subset))

for subset in all_subsets(stuff):
    print(list(subset))

但是输出是 enter image description here

1 个答案:

答案 0 :(得分:1)

如果您只希望包含1和2个元素的组合,则可以尝试itertools.combinations

>>> from itertools import combinations
>>> l = ["M", "M", "M", "C", "C", "C"]
>>> combs = set(list(combinations(l, 1)) + list(combinations(l, 2)))
>>> out = list(map(list, combs))
>>> print(out)
[['C', 'C'], ['M', 'M'], ['C'], ['M', 'C'], ['M']]