Home > Software design >  Convert comma separated string to list items in Python
Convert comma separated string to list items in Python

Time:10-08

I have a list like the following:

my_list = ['google', 'microsoft,facebook']

and I need to convert this into:

my_list = ['google', 'microsoft', 'facebook']

I tried doing it this way:

new_list = [item.split(',') for item in my_list]
flat_list = [item for sublist in new_list for item in sublist]

but this method involves unnecessary additional variables and multiple for loops. Is there a way we can make this easier?

CodePudding user response:

The below is simple enough (make en empty list and extend it)

my_list = ['google','microsoft,facebook']
new_list = []
for x in my_list:
  new_list.extend(x.split(','))
print(new_list)

output

['google', 'microsoft', 'facebook']

CodePudding user response:

You can do this by converting to the list to string and back to list as follows:

my_list = ['google','microsoft,facebook']

newList = ','.join(my_list).split(',')

Output:

['google', 'microsoft', 'facebook']

CodePudding user response:

You can do this in one nested comprehension:

new_list = [x for item in my_list for x in item.split(',')]

Or use itertools.chain:

from itertools import chain

new_list = [*chain(*(item.split(',') for item in my_list))]
# or the more traditional
new_list = list(chain.from_iterable(item.split(',') for item in my_list))

And if you want to go all out with the functional utils:

from functools import partial

new_list = [*chain(*map(partial(str.split, sep=","), my_list))]

CodePudding user response:

If you insist on doing it in-place, then you can do

for i,e in enumerate(my_list):
    my_list[i:i 1] = e.split(",")

CodePudding user response:

You can flat the list with sum(mylist, [])

l = ['google','microsoft,facebook']

ll = sum([s.split(',')  for s in l], [])

print(ll)

Output

['google', 'microsoft', 'facebook']
  • Related