0

I want to create a list from a list of items, where some of the items include values separated by commas. In other words, from

['a, b', 'c', 'd, e']

achieve

[['a', 'c', 'd'], ['a', 'c', 'e'], ['b', 'c', 'd'], ['b', 'c', 'e']]

I tried iterating over each item in nested loops, but the comma separation seems to be an issue.

Thanks in advance!

Walter
  • 79
  • 8
  • 1
    Try the split (',') method – Edo98 Nov 17 '20 at 09:13
  • Please update the question to show the code you've tried, it's output and *exactly* where you are stuck. – S3DEV Nov 17 '20 at 09:16
  • 1
    It's seems like you have to divide your problem to 2 steps (which both have answers here): 1) convert your list of strings to a nested list of letters ([how do you split a string to create nested list?](https://stackoverflow.com/questions/7680729/how-do-you-split-a-string-to-create-nested-list)) 2) Then get the combinations from this nested list ([All combinations of a list of lists](https://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists)) – Tomerikoo Nov 17 '20 at 09:44

1 Answers1

1

To tackle the problem of the comma separation we can split each string in the list.

data = ['a, b', 'c', 'd, e']
print([value.split(',') for value in data])

This gives us ['a', ' b'], ['c'], ['d', ' e']]

To get rid of those extra whitespaces we can modify the function by using map to apply str.strip to each resulting element of the inner list.

data = ['a, b', 'c', 'd, e']
print([list(map(str.strip, value.split(','))) for value in data])

The result is [['a', 'b'], ['c'], ['d', 'e']]

Now we can use itertools.product for the final combinations.

import itertools
data = ['a, b', 'c', 'd, e']
data_normalized = [list(map(str.strip, value.split(','))) for value in data]
print(list(itertools.product(*data_normalized)))

The result is [('a', 'c', 'd'), ('a', 'c', 'e'), ('b', 'c', 'd'), ('b', 'c', 'e')].

Matthias
  • 12,873
  • 6
  • 42
  • 48
  • Was trying to work this one out myself - thanks for introducing `product`. Learned something new today! – S3DEV Nov 17 '20 at 09:39