1

Say you have a list ['dogs, cats']. How can one turn that into ['dogs', 'cats'] for arbitrary number of ['x, y, z']

2
  • 2
    Could 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']? Commented Aug 9, 2013 at 19:45
  • 1
    Does your first list only have one element or can there be multiple elements that are comma separated strings? Commented Aug 9, 2013 at 19:47

2 Answers 2

7

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']
Sign up to request clarification or add additional context in comments.

Comments

0

Use split(', ') which gives you the List

list = ['dogs, cats', 'x, y, z']

finalList = []

for key in list: finalList.extend(key.split(', '))

you will get ['x', 'y', 'z', 'dogs', 'cats']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.