2

I want a list which is a combination of list of list elements For example: my input

x = [['P'], ['E', 'C'], ['E', 'P', 'C']]

The output should be

['PEE','PEP','PEC','PCE','PCP','PCC']]

Any help is highly appreciated.

Akash
  • 395
  • 5
  • 16

2 Answers2

4

Use itertools

[''.join(i) for i in itertools.product(*x)]

Note: assuming that last one should be 'PCC'

hspandher
  • 15,934
  • 2
  • 32
  • 45
1

here is a solution

def comb(character_list_list):
  res = ['']
  for character_list in character_list_list:
    res = [s+c for s in res for c in character_list]
  return res

On your example, it gives, as expected

>>> comb([['P'], ['E', 'C'], ['E', 'P', 'C']])
['PEE', 'PEP', 'PEC', 'PCE', 'PCP', 'PCC']

A shorter version is possible using functools.reduce(), but the use of this function is not recommanded.