itertools.groupby

Steve Howell showell30 at yahoo.com
Mon May 28 13:58:50 EDT 2007


--- Raymond Hettinger <python at rcn.com> wrote:

> That's not for everyone, so it isn't a loss if
> someone sticks
> with writing plain, clear everyday Python instead of
> an itertool.
> 

I know most of the module is fairly advanced, and that
average users can mostly avoid it, but this is a very
common-antipattern that groupby() solves:

    group = []
    lastKey = None
    for item in items:
        newKey = item.key()
        if newKey == lastKey:
            group.append(item)
        elif group:
            doSomething(group)
            group = []
        lastKey = newKey
    if group:
        doSomething(group)

See this recent thread, for example:

http://mail.python.org/pipermail/python-list/2007-May/442602.html





 
____________________________________________________________________________________
The fish are biting. 
Get more visitors on your site using Yahoo! Search Marketing.
http://searchmarketing.yahoo.com/arp/sponsoredsearch_v2.php



More information about the Python-list mailing list