Split a list based on index numbers given by another list

  • A+

Sorry I'm a beginner and looking for some help dealing with some data..

So I have two lists:

One describes all participants scores in a game The other contains the number of times each participant played the game

scores=['win', 'draw', 'lose', 'lose', 'win', 'win'] trials=[2,3,1] 

which means there were 3 participants, the first played two times and obtained 'win' and 'draw' etc.

How can I split the scores list so it becomes a nested list with each participants scores as a list? As I want to find a person's average score..

e.g. splitscores=[['win','draw']['lose','lose','win']['win]]

I've managed to get the first trial by doing:

trial1=[] for item in scores:     trial1.append(scores[:trials[0]]) print(trial1) 

but no clue to get the others by making a loop Can anyone help? Or is there a better way for me to find a person's average score?


The other answers are good. You can also do it with a simple for loop if you find that clearer:

scores = ['win', 'draw', 'lose', 'lose', 'win', 'win'] trials = [2, 3, 1] trial1 = [] # This variable holds the first index of the next sublist idx = 0 for n in trials:     trial1.append(scores[idx:idx + n])     # The next sublist starts where the previous one ended     idx += n print(trial1) 


[['win', 'draw'], ['lose', 'lose', 'win'], ['win']] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: