0

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']
5
  • 1
    There is no list in the list. It is still a string list. Commented Sep 15, 2022 at 10:49
  • 1
    What have you tried so far? Commented Sep 15, 2022 at 10:49
  • 1
    What does "the strs with multiple teams" mean? Where the output says, for example, '[Chelsea, Real Madrid, Sevilla]', did you mean ['Chelsea', 'Real Madrid', 'Sevilla']? Please read How to Ask and think about the logical steps needed to solve the problem. For example, can you write code that tells whether one of the original strings has multiple team names? Can you write code that creates the list for one of those strings? Can you write code that applies this process to each element of the list? If you put those things together, does it not solve the problem? Commented Sep 15, 2022 at 10:50
  • Check for comma and space ', ' in the string and if present - split at it Commented Sep 15, 2022 at 10:52
  • 1
    [str([x]) if ',' in x else x for x in data] Commented Sep 15, 2022 at 10:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Really appreciate that, I realised I made a mistake in the question and would ideally want to separate the teams within the nested lists
@order66 See edit. :)

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.