Sort a list with class objects as elements

I have a python list whose elements are class objects with various attributes, such as birthday_score, anniversary_score, baby_score ..... I want to sort the list based on one of these attributes, for example, year_score. How to do it?

+4
source share
4 answers
your_list.sort(key = lambda x : x.anniversary_score) 

or if the attribute name is a string, you can use:

 import operator your_list.sort(key=operator.attrgetter('anniversary_score')) 
+8
source

attrgetter convenient if you do not know the attribute name in advance (for example, perhaps it is a file or function parameter)

 from operator import attrgetter sorted(my_list, key=attrgetter('anniversary_score')) 
+5
source

Using sorted :

 class X(): def __init__(self, a_s): self.anniversary_score = a_s li = [X(1), X(2), X(3), X(4)] sorted(li, key=lambda x: x.anniversary_score) 

Typically, the Python Sorting Wiki has almost everything you will ever need to learn about sorting in Python.

+3
source

One way is to define in your class the __lt__() and __eq__() methods that tell Python how one instance of your class should be sorted compared to another:

 class A(): def __init__(self): self.sortattr = 'anniversary_score' # you can use 'baby_score', 'birthday_score' instead def __lt__(self, other): return getattr(self, self.sortattr) < getattr(other, other.sortattr) def __eq__(self, other): return getattr(self, self.sortattr) == getattr(other, other.sortattr) 

Then just use sort() , as for a list of numbers, strings, etc.:

  mylist.sort() # to sort in-place sorted(mylist) # to return a new sorted list 
+2
source

Source: https://habr.com/ru/post/1485569/


All Articles