2

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

0

2 Answers 2

4

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

Comments

1

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()

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.