Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting objects in Python

Tags:

python

sorting

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.

like image 846
Curious2learn Avatar asked Apr 07 '26 10:04

Curious2learn


2 Answers

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.

like image 58
Daniel Roseman Avatar answered Apr 09 '26 00:04

Daniel Roseman


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.

like image 36
SilentGhost Avatar answered Apr 08 '26 23:04

SilentGhost