Python implements sorting of custom class objects (using attrgetter)

不言
Release: 2018-10-20 14:50:03
forward
2422 people have browsed it

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')))
Copy after login

Running result:

[User(40), User(20), User(30)]
[User(20), User(30), User(40)]
[User(20), User(30), User(40)]
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template