Last active
December 12, 2017 16:30
-
-
Save harunyasar/65182502763e5dde8b68938b6f85eb2f to your computer and use it in GitHub Desktop.
attrget
This file contains 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 | |
from collections import namedtuple | |
# Example has been given from Aaron Maxwell's The Python Next Level source | |
class Student: | |
def __init__(self, name, major, gpa): | |
self.name = name | |
self.major = major | |
self.gpa = gpa | |
def __repr__(self): | |
return f"{self.name}: {self.gpa}" | |
student_objects = [ | |
Student("Joe Smith", "physics", 3.7), | |
Student("Jane Jones", "chemistry", 3.8), | |
Student("Zoe Grimwald", "literature", 3.4), | |
] | |
sort_by_gpa = sorted(student_objects, key=attrgetter("gpa")) | |
print(sort_by_gpa) | |
# attrget with sorted built-in functions also works with namedtuple | |
Student = namedtuple("Student", ["name", "major", "gpa"]) | |
student_objects = [ | |
Student("Joe Smith", "physics", 3.7), | |
Student("Jane Jones", "chemistry", 3.8), | |
Student("Zoe Grimwald", "literature", 3.4), | |
] | |
sort_by_gpa = sorted(student_objects, key=attrgetter("gpa")) | |
print(sort_by_gpa) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment