[Python-Dev] "groupby" iterator
gball at cfa.harvard.edu
Thu Nov 27 15:58:47 EST 2003
Here's a reworking which returns iterators. I had to decide what to do if
the user tries to access things out of order; I raise an exception.
Anything else would complicate the code quite a lot I think.
def groupby(key, iterable):
it = iter(iterable)
value = it.next() # If there are no items, this takes an early exit
oldkey = [key(value)]
cache = [value]
lock = 
for value in it:
newkey = key(value)
if newkey == oldkey:
oldkey = newkey
raise LookupError, "groups accessed out of order"
if not cache:
More information about the Python-Dev