Home > Blockchain >  Converting certain strings with a list into a nested list
Converting certain strings with a list into a nested list

Time:09-15

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

CodePudding user response:

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.

  • Related