Converting certain strings with a list into a nested list

Question:

I have a list that looks like so:

['Man City', 'Chelsea', 'Man City', 'Man City', 'Man City', 'Man City', 'Chelsea, Real Madrid, Sevilla', 'West Brom, Sunderland, PSG', 'Man City', 'Man City']

However, I want to change it so the strs with multiple teams become a list within the list

['Man City', 'Chelsea', 'Man City', 'Man City', 'Man City', 'Man City', ['Chelsea', 'Real Madrid', 'Sevilla'], ['West Brom', 'Sunderland', 'PSG'], 'Man City', 'Man City']
Asked By: order66

||

Answers:

Try this:

l = ['Man City', 'Chelsea', 'Man City', 'Man City', 'Man City', 'Man City', 'Chelsea, Real Madrid, Sevilla', 'West Brom, Sunderland, PSG', 'Man City', 'Man City']
print([x.split(", ") if ',' in x else x for x in l])

Result:

['Man City', 'Chelsea', 'Man City', 'Man City', 'Man City', 'Man City', ['Chelsea', 'Real Madrid', 'Sevilla'], ['West Brom', 'Sunderland', 'PSG'], 'Man City', 'Man City']

Edit to reflect comment. New output and edited code.

Answered By: user56700
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.