Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customized sort on list of objects

I have list of objects like

actors = [Person('Raj' ,'Hindi'),
          Person('John',  'English'),
          Person('Michael' 'Marathi'),
          Person('Terry','Hindi'),
          Person('Terry', 'Telugu')]

I want to sort this list of peoples depending on their mother tongue. In sequence Marathi, English, Hindi, Telugu. Means i want to sort objects in customized logic rather than in ascending or descending order.

I am using python 3.7. Could you please help me how can this be done ?

like image 845
Shirish Avatar asked Jan 26 '23 23:01

Shirish


2 Answers

You can do

sorted(actors, key = lambda x: mothertongue_list.index(x.tongue))

If we have that you can get mothertongue of Person by tongue and mothertongue_list is a list ordered as you want.

like image 91
Sergey Pugach Avatar answered Jan 29 '23 13:01

Sergey Pugach


Create a priority mapping of languages first:

priority_map = {v: k for k, v in enumerate(('Marathi', 'English', 'Hindi', 'Telugu'))}

Then use sorted with a custom key:

res = sorted(actors, key=lambda x: priority_map[x.tongue])

Alternatively, if applicable, make sorting a property of your class, as in this example.

like image 45
jpp Avatar answered Jan 29 '23 13:01

jpp