Summing a 2D list

Gerhard Häring gh at ghaering.de
Fri Jun 13 15:31:50 CEST 2008


BJörn Lindqvist wrote:
> [...]
> 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)

Except that this won't work unless users and scores are sorted by user 
first. groupby() only coalesces identical values, and doesn't do what a 
"GROUP BY" clause in SQL is doing.

Adding a sorted() call around zip() should be enough to make groupby() 
actually useful.

But then, this code definitely starts to look like somebody desperately 
wanted to find a use for Python's new gimmicks.

Here's more of the same sort ;-)

 >>> import sqlite3
 >>> sqlite3.connect(":memory:").execute("create table tmp(user, 
score)").executemany("insert into tmp(user, score) values (?, ?)", 
zip(users, scores)).execute("select user, sum(score) from tmp group by 
user").fetchall()
[(1, 6), (2, 4), (3, 2), (4, 8)]

-- Gerhard




More information about the Python-list mailing list