groupby and itemgetter

R

Roman Bertle

Hello,

there is an example how to use groupby in the itertools documentation
(http://docs.python.org/lib/itertools-example.html):

# Show a dictionary sorted and grouped by value.... print k, map(itemgetter(0), g)
....
1 ['a', 'c', 'e']
2 ['b', 'd', 'f']
3 ['g']

Now i wonder why itemgetter is used in this example. More
straightforward is:
.... print k, list(g)
....
1 ['a', 'c', 'e']
2 ['b', 'd', 'f']
3 ['g']

This code does not need the operator module, and its also faster (tested
using timeit). Why was the, imho, more complicated version used as
example in the documentation?

Regards, Roman
 
S

Steven Bethard

Roman said:
Hello,

there is an example how to use groupby in the itertools documentation
(http://docs.python.org/lib/itertools-example.html):

# Show a dictionary sorted and grouped by value... print k, map(itemgetter(0), g)
...
1 ['a', 'c', 'e']
2 ['b', 'd', 'f']
3 ['g']

Now i wonder why itemgetter is used in this example. More
straightforward is:
... print k, list(g)
...
1 ['a', 'c', 'e']
2 ['b', 'd', 'f']
3 ['g']

This code does not need the operator module, and its also faster (tested
using timeit).

It looks like it's even faster if you drop the iterkeys() call and just
write:

di = sorted(d, key=d.get)

As to why itemgetter is used, I don't really know...

STeVe
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top