Problem with itertools.groupby.

Fredrik Lundh fredrik at pythonware.com
Thu May 25 17:35:28 EDT 2006


trebucket at gmail.com wrote:

> What am I doing wrong here?
> 
>>>> import operator
>>>> import itertools
>>>> vals = [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15),
> ...      (1, 16), (2, 17), (3, 18), (4, 19), (5, 20)]
>>>> for k, g in itertools.groupby(iter(vals), operator.itemgetter(0)):
> ...     print k, [i for i in g]
> ...
> 1 [(1, 11)]
> 2 [(2, 12)]
> 3 [(3, 13)]
> 4 [(4, 14)]
> 5 [(5, 15)]
> 1 [(1, 16)]
> 2 [(2, 17)]
> 3 [(3, 18)]
> 4 [(4, 19)]
> 5 [(5, 20)]
> 
> What I want is tuples starting with identical numbers to be grouped.  I
> cannot figure out why this is not working.  If anyone has any insights,
> I would appreciate it.

itertools only looks for changes to the key value (the one returned by 
operator.itemgetter(0) in your case); it doesn't sort the list for you.

this should work:

   for k, g in itertools.groupby(sorted(vals), operator.itemgetter(0)):
      print k, [i for i in g]

</F>




More information about the Python-list mailing list