I want to sort objects using by one of their attributes. As of now, I am doing it in the following way
USpeople.sort(key=lambda person: person.utility[chosenCar],reverse=True)
This works fine, but I have read that using operator.attrgetter() might be a faster way to achieve this sort. First, is this correct? Assuming that it is correct, how do I use operator.attrgetter() to achieve this sort?
I tried,
keyFunc=operator.attrgetter('utility[chosenCar]')
USpeople.sort(key=keyFunc,reverse=True)
However, I get an error saying that there is no attribute 'utility[chosenCar]'.
The problem is that the attribute by which I want to sort is in a dictionary. For example, the utility attribute is in the following form:
utility={chosenCar:25000,anotherCar:24000,yetAnotherCar:24500}
I want to sort by the utility of the chosenCar using operator.attrgetter(). How could I do this?
Thanks in advance.
No, attrgetter will not be any faster than the lambda - it's really just another way of doing the same thing.
You may have been confused by a recommendation to use key instead of cmp, which is indeed significantly faster, but you're already doing that.
to access chosenCar item you'd have to use:
>>> P.utility={'chosenCar':25000,'anotherCar':24000,'yetAnotherCar':24500}
>>> operator.itemgetter('chosenCar')(operator.attrgetter('utility')(P))
25000
for the key function you'll have to do the following:
>>> def keyfunc(P):
util = operator.attrgetter('utility')(P)
return operator.itemgetter('chosenCar')(util)
>>> USpeople.sort(key=keyfunc,reverse=True)
However, your main claim re the better performance of this approach seems poorly researched. I'd suggest to use timeit module to test performance of both approaches for your own data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With