Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

Alex Martelli aleax at mac.com
Sun Sep 9 17:59:08 CEST 2007


Stefan Arentz <stefan.arentz at gmail.com> wrote:

> Miki <miki.tebeka at gmail.com> writes:
> 
> > >   steps.sort(key = lambda s: s.time)
> > This is why attrgetter in the operator module was invented.
> > from operator import attrgetter
> > ...
> > steps.sort(key=attrgettr("time"))
> 
> Personally I prefer the anonymous function over attrgettr :)

However, Python disagrees with you...:

brain:~ alex$ python -mtimeit -s'from operator import attrgetter;
L=map(complex,xrange(999))' 'sorted(L, key=lambda x:x.real)'
1000 loops, best of 3: 567 usec per loop

brain:~ alex$ python -mtimeit -s'from operator import attrgetter;
L=map(complex,xrange(999))' 'sorted(L, key=attrgetter("real"))'
1000 loops, best of 3: 367 usec per loop

A speed-up of 35% is a pretty clear indicator of what _Python_ "prefers"
in this situation:-).


Alex



More information about the Python-list mailing list