Customized sort on list of objects

Viewed 99

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 ?

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.

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.

Related