Simone
Simone

Reputation: 4940

How to create lists of combinations

I have generated all possible combinations using elements in a list, as explained here. Now, I would like to know how to save each combination as a list. I get this output:

[('A',),
 ('B',),
 ('A','B')
  ......]

I would get something like this:

[['A'],['B'],['AB'], ...... ]

Is there a simple way to implement it?

Upvotes: 0

Views: 89

Answers (4)

Strinnityk
Strinnityk

Reputation: 618

You could use map like so:

combinations = [('A',),
                ('B',),
                ('A','B')]

combinations_list = map(list, combinations)

Which would return a generator (Python3) or a list (Python2). If you want a list just cast it to list:

combinations_list = list(map(list, combinations))

This would convert the inner tuple structure to a list:

[("A"), ("B"), ("A", "B")] -> [["A"], ["B"], ["A", "B"]]

If you want to also flatten the tuple to get the following result:

[("A"), ("B"), ("A", "B")] -> [["A"], ["B"], ["AB"]]

You should change the first argument of the map for this:

lambda sub_tuple: ["".join(sub_tuple)]

Upvotes: 4

Thomas Kühn
Thomas Kühn

Reputation: 9810

Following the example linked by the OP:

from itertools import combinations
lis = ['A', 'B', 'C', 'D']
result = []
for i in range(1, len(lis)+1):  

    result+=[''.join(c) for c in combinations(lis, i)]

print(result)

gives

['A', 'B', 'C', 'D', 'AB', 'AC', 'AD', 'BC', 'BD', 'CD', 'ABC', 'ABD', 'ACD', 'BCD', 'ABCD']

EDIT:

The same as one-liner:

result = [''.join(c) for i in range(1,len(lis)+1) for c in combinations(lis,i)]

Upvotes: 1

MSeifert
MSeifert

Reputation: 152587

You could use a list comprehension with str.join:

>>> combinations = [('A',), ('B',), ('A','B')]
>>> [[''.join(comb)] for comb in combinations]
[['A'], ['B'], ['AB']]

Instead of the list-comprehension you could also use a generator expression:

>>> combs_as_lists = ([''.join(comb)] for comb in combinations)
>>> for comb in combs_as_lists:
...     print(comb)
['A']
['B']
['AB']

Upvotes: 0

khelwood
khelwood

Reputation: 59096

If you're saying you have a list of tuples, and you want a list of lists, you can convert it using

list_of_lists = [list(t) for t in list_of_tuples]

or you could use map.

In Python 2:

list_of_lists = map(list, list_of_tuples)

In Python 3:

list_of_lists = list(map(list, list_of_tuples))

Upvotes: 3

Related Questions