Suppose a set of objects of the same class, the class does not implement local comparison. Now I want to sort based on an attribute class.
Conventional practice is customized parameter key sorted keyword comparison method, the following example:
class User:
def __init__(self, user_id):
self.user_id = user_id
def __repr__(self):
return 'User({})'.format(self.user_id)
>>> users = [User(23), User(3), User(99)]
>>> users
[User(23), User(3), User(99)]
>>> sorted(users, key=lambda u: u.user_id)
[User(3), User(23), User(99)]
>>>
An alternative is to use the operator module attrgetter function, as follows:
>>> from operator import attrgetter
>>> sorted(users, key=attrgetter('user_id'))
[User(3), User(23), User(99)]
Conventional lambda or attrgetter based on personal preference, but attrgetter superior in performance, and adds a property that can support more than one class attribute domains simultaneously. . attrgetter on a similar Bowen itemgetter usage.