how to convert a string with comma separated values within a list in python?

Viewed 93

Hi I'm relatively new to python and not quite getting a resolve for the mentioned issue

I have an input list ['abc','def','asd,trp','faq']

Expected Output list ['abc','def','asd','trp','faq']

please help in achieving the same

2 Answers

Use split in list comprehension:

L = ['abc','def','asd,trp','faq']

L1 = [y for x in L for y in x.split(',')]
print (L1)
['abc', 'def', 'asd', 'trp', 'faq']
    

You can iterate over the list and check if a comma exists and if it does, split and extend, if not, append to an output list.

lst = ['abc','def','asd,trp','faq']
out = []
for item in lst:
    if ',' in item:
        out.extend(item.split(','))
    else:
        out.append(item)

Output:

['abc', 'def', 'asd', 'trp', 'faq']

Since you tagged pandas, using pandas, you can also do:

out = pd.Series(lst).str.split(',').explode().tolist()
Related