简体   繁体   English

Python:列表中每个可能的子集组合

[英]Python: every possible subset combination from a list

i have a list:我有一个清单:

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

i want the output to be我希望 output 成为

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

how to do this?这该怎么做? Thanks in advance!提前致谢!

I have used this code:我用过这段代码:

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

but the output is但是 output 是在此处输入图像描述

If you only want combinations with 1 and 2 elements then maybe try itertools.combinations :如果您只想要 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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM