Merging sorted lists/iterators/generators into one stream of values...

George Sakkis gsakkis at rutgers.edu
Tue Oct 11 09:23:56 EDT 2005


> Function name is perhaps not the best one. It occurs to me that this
> is the GROUP BY in SQL so perhaps a different name is better, but
> then again this might be moot if such a already exists somewhere :)

Amazing, you keep reinventing things, even with the exact same name :)

from itertools import imap,groupby
from operator import itemgetter

for fruit,group in groupby(fruits, itemgetter(0)):
    print fruit, "has a sum of", sum(imap(itemgetter(1),group))

For this to work as intended, fruits has to be already sorted by the
same key given to grouby; otherwise just replace fruits with
sorted(fruits, itemgetter(0)).

By the way, read all the functions in the itertools module
(http://docs.python.org/lib/itertools-functions.html), it will save you
a lot of time.

George




More information about the Python-list mailing list