itertools.groupby

T

Tobiah

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
 
P

Paul Rubin

Tobiah said:
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)
 
T

Tobiah

Paul said:
Tobiah said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top