Cha*_*wal 4 python sorting class list
i have a python list whose items are objects of a class with various attributes such as birthday_score, anniversary_score , baby_score..... I want to to sort the list on the basis of one of these attributes ,say anniversary_score. How do i do it ?
your_list.sort(key = lambda x : x.anniversary_score)
Run Code Online (Sandbox Code Playgroud)
或者如果属性名称是字符串,那么您可以使用:
import operator
your_list.sort(key=operator.attrgetter('anniversary_score'))
Run Code Online (Sandbox Code Playgroud)
attrgetter 如果您事先不知道属性的名称(例如,可能来自文件或函数参数),则很方便
from operator import attrgetter
sorted(my_list, key=attrgetter('anniversary_score'))
Run Code Online (Sandbox Code Playgroud)