4

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 ?

jpp
  • 134,728
  • 29
  • 196
  • 240
Shirish
  • 53
  • 7

2 Answers2

5

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.

Sergey Pugach
  • 4,563
  • 1
  • 10
  • 26
  • 3
    Probably better to create a dict `{tongue: index}` and than lookup the index in that dict instead of using `index`. Otherwise fine. – tobias_k Dec 21 '18 at 11:17
  • @tobias_k why `dict` instead of `list.index`? Any particular reason? – Mortz Dec 21 '18 at 11:25
  • 4
    @Mortz, `list.index` has O(n) complexity, `dict.get` or `dict.__getitem__` has O(1) time complexity. – jpp Dec 21 '18 at 11:26
  • Wow, amazing. Thanks. Does this have to do with the fact that a dict is a hash table? – Mortz Dec 21 '18 at 11:28
  • 2
    @Mortz, Yes, exactly. Hashing enables O(1) lookup. – jpp Dec 21 '18 at 11:33
  • Thanks for the help! Is there any concept of comparator in Python like we have in Java. https://stackoverflow.com/questions/2839137/how-to-use-comparator-in-java-to-sort – Shirish Dec 22 '18 at 06:23
3

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.

jpp
  • 134,728
  • 29
  • 196
  • 240
  • Thanks for the help! Is there any concept of comparator in Python like we have in Java. https://stackoverflow.com/questions/2839137/how-to-use-comparator-in-java-to-sort – Shirish Dec 22 '18 at 06:23
  • @Shirish, Don't believe so, the closest you'll find is probably [this OOP approach](https://stackoverflow.com/a/48731059/9209546). – jpp Dec 24 '18 at 14:26