Say you have a list ['dogs, cats']. How can one turn that into ['dogs', 'cats'] for arbitrary number of ['x, y, z']
-
2Could you clarify what you mean by "list of unique substrings"? Your example isn't making it clear to me - maybe provide another example? Do you just want to split any string of the form 'a, b, c, ..., n' into ['a', 'b', 'c', ..., 'n']?Brionius– Brionius2013-08-09 19:45:15 +00:00Commented Aug 9, 2013 at 19:45
-
1Does your first list only have one element or can there be multiple elements that are comma separated strings?AlexLordThorsen– AlexLordThorsen2013-08-09 19:47:51 +00:00Commented Aug 9, 2013 at 19:47
Add a comment
|
2 Answers
Just split the first element on ', ':
>>> ['dogs, cats'][0].split(', ')
['dogs', 'cats']
>>>
>>> ['x, y, z'][0].split(', ')
['x', 'y', 'z']
If you can have multiple comma separated string in your list, then you can use list comprehension:
>>> li = ['x, y, z', 'dogs, cats']
>>>
>>> li2 = [elem.split(', ') for elem in li]
>>> [v for val in li2 for v in val]
['x', 'y', 'z', 'dogs', 'cats']
Or using sum() over list comprehension:
>>> li = ['x, y, z', 'dogs, cats']
>>>
>>> sum([elem.split(', ') for elem in li], [])
['x', 'y', 'z', 'dogs', 'cats']
And finally itertools:
>>> list(itertools.chain.from_iterable(elem.split(', ') for elem in li))
['x', 'y', 'z', 'dogs', 'cats']