Created
April 10, 2015 14:12
-
-
Save Averroes/e487518a228b76fa929b to your computer and use it in GitHub Desktop.
sort objects without native comparison support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from operator import attrgetter | |
| class User: | |
| def __init__(self, user_id): | |
| self.user_id = user_id | |
| def __repr__(self): | |
| return 'User({})'.format(self.user_id) | |
| # Example | |
| users = [User(23), User(3), User(99)] | |
| print(users) | |
| # Sort it by user-id | |
| print(sorted(users, key=attrgetter('user_id'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment