Home > Article > Backend Development > Python implements sorting of custom class objects (using attrgetter)
The content of this article is about the Python implementation of sorting custom class objects (using attrgetter). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Requirements
Sort the list of custom classes.2. Solution
The built-in sorted() function can accept a parameter key used to pass a callable object (callable), and the callable object will return to be Certain values in an object are sorted, and sorted uses these values to compare the objects.
Example:
from operator import attrgetter class User: def __init__(self,userId): self.userId=userId def __repr__(self): return 'User({})'.format(self.userId) users=[User(40),User(20),User(30)] print(users) #方法1 print(sorted(users,key=lambda u:u.userId)) #方法2 print(sorted(users,key=attrgetter('userId')))
Running result:
[User(40), User(20), User(30)] [User(20), User(30), User(40)] [User(20), User(30), User(40)]
attrgetter is usually a little faster. The above counting also applies to the min() and max() functions.
The above is the detailed content of Python implements sorting of custom class objects (using attrgetter). For more information, please follow other related articles on the PHP Chinese website!