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

Time:12-20

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

CodePudding user response:

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']
    

CodePudding user response:

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']
  • Related