3

If I have a list of tuples, where the first is number, and second is a string, for example:

[(2, 'eye'), (4, 'tail'), (1, 'scarf'), (4,'voice')]

How can I sort it in descending order by the number and If there is a tie in number at any point, the words with the same number should be sub-sorted alphabetically. And return the final sorted words.

From my example:

['tail', 'voice', 'eye', scarf']

I sorted them by descending order, but I don't know how to subsort it alphabetically. Will be happy to hear any hint and answer. Thanks!

def sorting(list)
   my_list = []
   for x, y in list.items():
     my_list+=[(y,x)]
   sort=sorted(my_list, reverse=True)
EnriMR
  • 3,924
  • 5
  • 39
  • 59
Leyla
  • 69
  • 1
  • 8

1 Answers1

11

You can use the key argument , move the number (first element) to its negative counter-part and sort that list in ascending order. Example -

In [21]: lst = [(2, 'eye'), (4, 'tail'), (1, 'scarf'), (4,'voice')]

In [22]: sorted(lst, key = lambda x: (-x[0],x[1]))
Out[22]: [(4, 'tail'), (4, 'voice'), (2, 'eye'), (1, 'scarf')]

To get only the list of words in that order, you can use list comprehension -

In [24]: [x[1] for x in sorted(lst, key = lambda x: (-x[0],x[1]))]
Out[24]: ['tail', 'voice', 'eye', 'scarf']
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • Various sorting questions are answered in [this](https://wiki.python.org/moin/HowTo/Sorting#Ascending_and_Descending) document, which also shows an idiomatic way of using the 'key' parameter. – nullop Sep 14 '15 at 12:25