-2

I have a list of elements like:

x = ['A, B', '2', '3', 'Jan, Feb']
#      ^                   ^
#    comma separated single string

I want to transform this list into a list of lists with all the combinations of each element that is comma separated so that it looks like:

[['A', '2', '3', 'Jan'], ['A', '2', '3', 'Feb']
 ['B', '2', '3', 'Jan'], ['B', '2', '3', 'Feb']]

What is the elegant way to achieve this using Python's in-built functions/libraries?

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Bob Ezuba
  • 510
  • 1
  • 5
  • 22

1 Answers1

5

You may firstly split the elements of list based on comma , and then use itertools.product to get the desired list as:

from itertools import product
x = ['A, B', '2', '3', 'Jan, Feb']

new_list = list(product(*[i.split(', ') for i in x]))

where content of new_list will be:

[('A', '2', '3', 'Jan'), 
 ('A', '2', '3', 'Feb'), 
 ('B', '2', '3', 'Jan'), 
 ('B', '2', '3', 'Feb')]

Based on Dan D's comment, below is the timeit comparison of intermediate List V/s intermediate generator comparison on Python 2. Intermediate list expression is slightly faster:

mquadri$ python -m timeit "from itertools import product; list(product(*(i.split(', ') for i in ['A, B', '2', '3', 'Jan, Feb'])))"
100000 loops, best of 3: 4.83 usec per loop

mquadri$ python -m timeit "from itertools import product; list(product(*[i.split(', ') for i in ['A, B', '2', '3', 'Jan, Feb']]))"
100000 loops, best of 3: 3.78 usec per loop
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126