Summing a 2D list

Benjamin Kaplan benjamin.kaplan at case.edu
Thu Jun 12 10:08:44 EDT 2008


On Thu, Jun 12, 2008 at 9:48 AM, 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.
>
> Any help much appreciated,
>

If your data is set up as a list of tuples or lists, you can try using a
dictionary for the final count, since each user will have only one final
entry. Then, you can check to see if the user already has an entry in the
dict so you know if you should create a new entry or just add to the old
one.

firstList = [your pairs of data]
totals = {}
for i, j in firstList :
   if i in totals :
      totals[i] += j
   else :
      totals[i] = j


>
> Mark
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080612/9d1c758b/attachment.html>


More information about the Python-list mailing list