itertools.groupby

George Sakkis george.sakkis at gmail.com
Tue May 29 23:30:14 EDT 2007


On May 29, 2:34 am, Raymond Hettinger <pyt... at rcn.com> wrote:

> If the posters on this thread have developed an interest
> in the subject, I would find it useful to hear their
> ideas on new and creative ways to use groupby().  The
> analogy to UNIX's uniq filter was found only after the
> design was complete.  Likewise, the page numbering trick
> (shown above by Paul and in the examples in the docs)
> was found afterwards.  I have a sense that there are entire
> classes of undiscovered use cases which would emerge
> if serious creative effort where focused on new and
> interesting key= functions (the page numbering trick
> ought to serve as inspiration in this regard).
>
> The gauntlet has been thrown down.  Any creative thinkers
> up to the challenge?  Give me cool recipes.

Although obfuscated one-liners don't have a large coolness factor in
Python, I'll bite:

from itertools import groupby
from random import randint
x = [randint(0,100) for _ in xrange(20)]
print x
n = 7
# <-- insert fat comments here about the next line --> #
reduce(lambda acc,(rem,divs): acc[rem].extend(divs) or acc,
              groupby(x, key=lambda div: div%n),
              [[] for _ in xrange(n)])


George




More information about the Python-list mailing list