简体   繁体   中英

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

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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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