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

Lasse Vågsæther Karlsen lasse at vkarlsen.no
Tue Oct 11 09:29:22 EDT 2005


George Sakkis wrote:
>>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
> 

Itertools, meh, there's that wheel again :)

Didn't know about this one so thank you :)

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:lasse at vkarlsen.no
PGP KeyID: 0x2A42A1C2



More information about the Python-list mailing list