1

I have a list of values in which some values are words separated by commas, but are considered single strings as shown:

l = ["a",
     "b,c",
     "d,e,f"]

#end result should be
#new_list = ['a','b','c','d','e','f']

I want to split those strings and was wondering if there's a one liner or something short to do such a mutation. So far what, I was thinking of just iterating through l and .split(',')-ing all the elements then merging, but that seems like it would take a while to run.

4 Answers 4

1
import itertools
new_list = list(itertools.chain(*[x.split(',') for x in l]))

print(new_list)
>>> ['a', 'b', 'c', 'd', 'e', 'f']
Sign up to request clarification or add additional context in comments.

Comments

1

Kind of unusual but you could join all your elements with , and then split them:

l = ["a",
     "b,c",
     "d,e,f"]

newList = ','.join(l).split(',')
print(newList)

Output:

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

1 Comment

I like this solution. It just takes a bit longer than the one liner posted by @Blorgbeard. Still a great solution though!
0

Here's a one-liner using a (nested) list comprehension:

new_list = [item for csv in l for item in csv.split(',')]

See it run here.

Comments

0

Not exactly a one-liner, but 2 lines:

>>> l = ["a",
     "b,c",
     "d,e,f"]
>>> ll =[]
>>> [ll.extend(x.split(',')) for x in l]
[None, None, None]
>>> ll
['a', 'b', 'c', 'd', 'e', 'f']

The accumulator needs to be created separately since x.split(',') can not be unpacked inside a comprehension.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.