A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2003-November/040480.html below:

[Python-Dev] "groupby" iterator

[Python-Dev] "groupby" iterator [Python-Dev] "groupby" iteratorGreg Ball 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 = []
    def grouper():
        yield cache.pop()
        for value in it:
            newkey = key(value)
            if newkey == oldkey[0]:
                yield value
            else:
                oldkey[0] = newkey
                cache.append(value)
                break
        del lock[0]
    while 1:
        if lock:
            raise LookupError, "groups accessed out of order"
        if not cache:
            break
        lock.append(1)
        yield grouper()


--Greg Ball



More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4