I. Evans
I. Evans

Reputation: 155

Split a list based on index numbers given by another list

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?

Upvotes: 4

Views: 102

Answers (3)

RoadRunner
RoadRunner

Reputation: 26315

You can call next() by converting scores to a list iterator with iter():

>>> scores=['win', 'draw', 'lose', 'lose', 'win', 'win']
>>> trials=[2,3,1]
>>> scores = iter(scores)
>>> [[next(scores) for i in range(j)] for j in trials]
[['win', 'draw'], ['lose', 'lose', 'win'], ['win']]

Upvotes: 4

javidcf
javidcf

Reputation: 59701

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

Upvotes: 4

jpp
jpp

Reputation: 164673

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

Upvotes: 5

Related Questions