[英]Finding all list and sublist combination from flat list
I'm trying to find an elegant way to generate all possible combinations from an initial flat list.我试图找到一种优雅的方式来从初始平面列表中生成所有可能的组合。
For example:例如:
[In:] [在:]
l = ["aaa", "bbb", "ccc"]
[Out:] [出去:]
[["aaa"], ["bbb"], ["ccc"]]
[["aaa", "bbb"], ["ccc"]]
[["aaa", "ccc"], ["bbb"]]
[["bbb", "ccc"], ["aaa"]]
[["aaa", "bbb", "ccc"]]
As you see here the order doesn't matter for me.正如你在这里看到的,顺序对我来说无关紧要。 So I would avoid to obtain such cases:
所以我会避免获得这样的情况:
[["aaa"], ["bbb"], ["ccc"]]
[["bbb"], ["aaa"], ["ccc"]]
...
[["ccc"], ["aaa"], ["bbb"]]
Also each sublist of my output list has to contain every element of my initial list.此外,我的输出列表的每个子列表都必须包含我的初始列表的每个元素。
I din't find any obvious solution with itertools.combination()
我没有找到任何明显的解决方案
itertools.combination()
Thanks谢谢
Question is quite vague, I think what you are looking for is set-partitions:问题很模糊,我认为您正在寻找的是设置分区:
def partition(collection):
if len(collection) == 1:
yield [ collection ]
return
first = collection[0]
for smaller in partition(collection[1:]):
# insert `first` in each of the subpartition's subsets
for n, subset in enumerate(smaller):
yield smaller[:n] + [[ first ] + subset] + smaller[n+1:]
# put `first` in its own subset
yield [ [ first ] ] + smaller
something = ['a', 'b', 'c']
for n, p in enumerate(partition(something), 1):
print(n, sorted(p))
Output:输出:
1 [['a', 'b', 'c']]
2 [['a'], ['b', 'c']]
3 [['a', 'b'], ['c']]
4 [['a', 'c'], ['b']]
5 [['a'], ['b'], ['c']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.