# "groupby" is brilliant!

James Stroud jstroud at ucla.edu
Wed Jun 14 21:55:27 CEST 2006

```Alex Martelli wrote:
> James Stroud <jstroud at ucla.edu> wrote:
>    ...
>
>>def doit(rows, doers, i=0):
>>   for r, alist in groupby(rows, itemgetter(i)):
>>     if len(doers) > 1:
>>       doit(alist, doers[1:], i+1)
>>     doers[0](r)
>
>
> Isn't this making N useless slices (thus copies, for most kinds of
> sequences) for a doers of length N?  Since you're passing i anyway, it
> seems to me that:
>
> def doit(rows, doers, i=0):
>     for r, alist in groupby(rows, itemgetter(i)):
>       if len(doers) > i+1:
>          doit(alist, doers, i+1)
>       doers[i](r)
>
> is equivalent to your code, but avoids these slices (thus copies).
>
>
> Alex

Actually, I remember why I wrote it that way--because the itemgetter
argument may not start at zero (admitting that I haven't yet played with
itemgetter at all). Maybe pop(0) is better than a copy?

def doit(rows, doers, i=0):
for r, alist in groupby(rows, itemgetter(i)):
doer = doers.pop(0)
if doers:                  # empty list tests as False
doit(alist, doers, i+1)
doer(r)

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/

```