Not limited to Python, when writing a program, there are many opportunities to sort lists (arrays) and dictionaries. And many of those methods are introduced in blog articles and so on.
However, less often than lists and dictionaries, there are times when you want to sort a list of instances by instance variables. For example, if you have the following class called Student
, you might sort the list of instances named students
by score
.
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
a = Student('Taro', 70)
b = Student('Hanako', 90)
c = Student('Jiro', 80)
students = [a, b, c]
In such a case, if you use the operator.attrgetter function, it will take a few lines (almost one line) as follows. Can write.
from operator import attrgetter
students.sort(key=attrgetter('score'))
for s in students:
print(s.name, s.score)
Taro 70
Jiro 80
Hanako 90
If you want to sort in descending order, just set the sort
method argument reverse
to True
as follows:
from operator import attrgetter
students.sort(key=attrgetter('score'), reverse=True)
for s in students:
print(s.name, s.score)
Hanako 90
Jiro 80
Taro 70
Recommended Posts