Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list based on index numbers given by another list

Tags:

python

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?

like image 949
I. Evans Avatar asked Dec 10 '22 04:12

I. Evans


2 Answers

You can use itertools.accumulate to sum your trials list cumulatively. Then use a list comprehension with slicing:

from itertools import accumulate

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

idx = [0] + list(accumulate(trials))
res = [scores[start:end] for start, end in zip(idx, idx[1:])]

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

For a truly lazy solution, you can use the itertools pairwise recipe:

from itertools import accumulate, tee

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

idx = accumulate([0] + trials)
res = [scores[start:end] for start, end in pairwise(idx)]

[['win', 'draw'], ['lose', 'lose', 'win'], ['win']]
like image 77
jpp Avatar answered Mar 08 '23 01:03

jpp


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)

Output:

[['win', 'draw'], ['lose', 'lose', 'win'], ['win']]
like image 44
jdehesa Avatar answered Mar 08 '23 01:03

jdehesa