-1

Working through a combinations problem and attempting to output a list with a list of lists as input. Closest solution that I've found is here: All combinations of a list of lists

However, I do not want all combinations between lists, but within each list. For example

[[1],[2,3],[4,5,6]] -> [[1],[2],[3],[2,3],[4],[5],[6],[4,5],[4,6],            
[5,6],[4,5,6]]
Matt
  • 21
  • 7
  • How deep can this list be? Will it only ever be a list of lists? Also, does the order of the output list matter? – Matt Hall Apr 29 '19 at 18:16

3 Answers3

3

Credit to How can I find all the subsets of a set, with exactly n elements?

First find a way to find all subsets for one list (also called the power set):

from itertools import chain, combinations

def powerset(iterable):
    """
    powerset([1,2,3]) --> [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
    """
    xs = list(iterable)
    return [list(x) for x in chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1)) if x]

Then iterate for each list:

list_of_list = [[1],[2,3],[4,5,6]]
result = []
for x in list_of_list:
    result += powerset(x)
print(result)

Output:

[[1], [2], [3], [2, 3], [4], [5], [6], [4, 5], [4, 6], [5, 6], [4, 5, 6]]
1

Below, I define a helper function to get all of the combinations from a sequence, then apply that to every sublist of your input list and chain the results together.

from itertools import chain, combinations

l=[[1],[2,3],[4,5,6]]

def all_comb(seq):
    return chain.from_iterable(combinations(seq, i) for i in range(1, len(seq)+1))

print(list(chain.from_iterable(map(all_comb, l))))
# [(1,), (2,), (3,), (2, 3), (4,), (5,), (6,), (4, 5), (4, 6), (5, 6), (4, 5, 6)]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

with itertools.combinations:

from itertools import combinations

l = [[1],[2,3],[4,5,6]]

combos = sum([[list(c) for c in combinations(x, i)] for x in l for i in range(1, len(x)+1)], [])

combos
>>> [[1], [2], [3], [2, 3], [4], [5], [6], [4, 5], [4, 6], [5, 6], [4, 5, 6]]
Lante Dellarovere
  • 1,838
  • 2
  • 7
  • 10