Summing a 2D list

BJörn Lindqvist bjourne at gmail.com
Fri Jun 13 08:58:37 EDT 2008


On Thu, Jun 12, 2008 at 3:48 PM, Mark <markjturner at gmail.com> wrote:
> Hi all,
>
> I have a scenario where I have a list like this:
>
> User            Score
> 1                 0
> 1                 1
> 1                 5
> 2                 3
> 2                 1
> 3                 2
> 4                 3
> 4                 3
> 4                 2
>
> And I need to add up the score for each user to get something like
> this:
>
> User            Score
> 1                 6
> 2                 4
> 3                 2
> 4                 8
>
> Is this possible? If so, how can I do it? I've tried looping through
> the arrays and not had much luck so far.

Here is another solution:

from itertools import groupby
from operator import itemgetter

users = [1, 1, 1, 2, 2, 3, 4, 4, 4]
scores = [0, 1, 5, 3, 1, 2, 3, 3, 2]

for u, s in groupby(zip(users, scores), itemgetter(0)):
    print u, sum(y for x, y in s)

You probably should reconsider how you can store your data in a more
efficient format.

-- 
mvh Björn



More information about the Python-list mailing list