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

Stefan Arentz stefan.arentz at gmail.com
Mon Sep 10 07:10:24 EDT 2007


aleax at mac.com (Alex Martelli) writes:

> 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:-).

I could not care less :-)

 S.



More information about the Python-list mailing list