[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

itertools.groupby

Tobiah

1/15/2008 8:29:00 PM

In the docs and examples that I have seen so far,
it is suggested that the groupby() input list may be pre-sorted
with the same function that is passed to groupby as
a key extractor.

I tried doing this with a simple example, but noticed
that [].sort(func) passes two arguments to func, whereas
the function expected by groupby() uses only one argument.

It would seem that two differently written functions would
have to be created which operate on the data in conceptually
similar but practically different ways in order to presort
the input list so that semantically similar items all make
it into the same group.

Thanks,

Toby

--
Posted via a free Usenet account from http://www.te...

2 Answers

Paul Rubin

1/16/2008 8:12:00 AM

0

Tobiah <toby@tobiah.org> writes:
> I tried doing this with a simple example, but noticed
> that [].sort(func) passes two arguments to func, whereas
> the function expected by groupby() uses only one argument.

Use: [].sort(key=func)

Tobiah

1/16/2008 7:58:00 PM

0

Paul Rubin wrote:
> Tobiah <toby@tobiah.org> writes:
>> I tried doing this with a simple example, but noticed
>> that [].sort(func) passes two arguments to func, whereas
>> the function expected by groupby() uses only one argument.
>
> Use: [].sort(key=func)

Oh cool. Thanks.

Only in 2.4+ it seems.


>>> a = [1,2,3,4,5]
>>> def sorter(thing):
.... return thing % 2 == 0
....
>>> a.sort(key = sorter)
>>> print a
[1, 3, 5, 2, 4]
>>>


Nifty

--
Posted via a free Usenet account from http://www.te...