itertools.groupby

Carsten Haese carsten at uniqsys.com
Sun May 27 15:47:01 EDT 2007


On Sun, 2007-05-27 at 10:17 -0700, 7stud wrote:
> Bejeezus.  The description of groupby in the docs is a poster child
> for why the docs need user comments.  Can someone explain to me in
> what sense the name 'uniquekeys' is used this example:
> 
> 
> import itertools
> 
> mylist = ['a', 1, 'b', 2, 3, 'c']
> 
> def isString(x):
>     s = str(x)
>     if s == x:
>         return True
>     else:
>         return False
> 
> uniquekeys = []
> groups = []
> for k, g in itertools.groupby(mylist, isString):
>     uniquekeys.append(k)
>     groups.append(list(g))
> 
> print uniquekeys
> print groups
> 
> --output:--
> [True, False, True, False, True]
> [['a'], [1], ['b'], [2, 3], ['c']]

The so-called example you're quoting from the docs is not an actual
example of using itertools.groupby, but suggested code for how you can
store the grouping if you need to iterate over it twice, since iterators
are in general not repeatable.

As such, 'uniquekeys' lists the key values that correspond to each group
in 'groups'. groups[0] is the list of elements grouped under
uniquekeys[0], groups[1] is the list of elements grouped under
uniquekeys[1], etc. You are getting surprising results because your data
is not sorted by the group key. Your group key alternates between True
and False.

Maybe you need to explain to us what you're actually trying to do.
User-supplied comments to the documentation won't help with that.

Regards,

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





More information about the Python-list mailing list