Sorting objects in Python

I want to sort objects using one of their attributes. At the moment I am doing it as follows

USpeople.sort(key=lambda person: person.utility[chosenCar],reverse=True)

This works fine, but I read that using operator.attrgetter () can be a faster way to achieve this kind of thing. Firstly, is this correct? Assuming this is correct, how can I use operator.attrgetter () to achieve this kind?

I tried,

 keyFunc=operator.attrgetter('utility[chosenCar]')
 USpeople.sort(key=keyFunc,reverse=True)

However, I get an error message indicating that the attribute 'utility [selectedCar] does not exist.

The problem is that the attribute by which I want to sort is in the dictionary. For example, a utility attribute has the following form:

utility={chosenCar:25000,anotherCar:24000,yetAnotherCar:24500}

I want to sort using the selectedCar utility with operator.attrgetter (). How can i do this?

Thanks in advance.

+3
3

chosenCar, :

>>> P.utility={'chosenCar':25000,'anotherCar':24000,'yetAnotherCar':24500}
>>> operator.itemgetter('chosenCar')(operator.attrgetter('utility')(P))
25000

key :

>>> def keyfunc(P):
    util = operator.attrgetter('utility')(P)
    return operator.itemgetter('chosenCar')(util)

>>> USpeople.sort(key=keyfunc,reverse=True)

, : . timeit .

+1

, attrgetter , - .

, key cmp, , .

+2
+1

Source: https://habr.com/ru/post/1743486/


All Articles