itertools.groupby

Carsten Haese carsten at uniqsys.com
Sun May 27 20:31:28 EDT 2007


On Sun, 2007-05-27 at 14:59 -0700, Steve Howell wrote:
> Huh?  How is code that uses itertools.groupby not an
> actual example of using itertools.groupby?

Here's how:

"""
The returned group is itself an iterator that shares the underlying
iterable with groupby(). Because the source is shared, when the groupby
object is advanced, the previous group is no longer visible. So, if that
data is needed later, it should be stored as a list:

    groups = []
    uniquekeys = []
    for k, g in groupby(data, keyfunc):
        groups.append(list(g))      # Store group iterator as a list
        uniquekeys.append(k)
"""

It does not say "Here is an example for how to use itertools.groupby."
It's an abstract code pattern for an abstract use case. There is an
example on the following page, called Examples!

> These docs need work.  Please do not defend them;

The docs do their job in specifying what groupby does. Providing code
snippets is not the job of the documentation. There are plenty of other
resources with code snippets.

To name just one, there's an example of itertools.groupby in the last
code snippet at
http://informixdb.blogspot.com/2007/04/power-of-generators-part-two.html

> please suggest improvements.

Why should I? The docs suit my needs just fine. Of course, that
shouldn't stop you from suggesting improvements.

Best regards,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list