Archive
Posts Tagged ‘operator’
Sort a list of objects by an attribute / function value
September 10, 2011
Leave a comment
Problem
You have a list of objects that you would like to sort by an attribute.
Solution
import operator
countries.sort(key=operator.attrgetter("population"), reverse=False)
Here countries is a list of Country objects. In the Country class there is an attribute called “population“. It will sort the countries in ascending order by the number of population.
Update (20110911)
Of course, you can also sort a list of objects by the value of a function. For instance, you have a class Student and the grades are stored in a list. You want to sort the students by the average of their grades. This value is calculated by the function get_avg_grade().
import operator
# students is a list of Student objects
students.sort(key=operator.methodcaller("get_avg_grade"), reverse=False)
Categories: python
attrgetter, methodcaller, operator, sort by attribute, sort by function value, sort objects
