0

I am trying to sort a list which has tuples consisting of a word and a number.

my_list = [('hello',25), ('hell',4), ('bell',4)]

How can i sort this (using lambda maybe) so that i get

[('hello',25), ('bell',4), ('hell',4)]
Chillar Anand
  • 27,936
  • 9
  • 119
  • 136
Abhishek Verma
  • 73
  • 1
  • 1
  • 5

2 Answers2

2

The easiest way is to take advantage of sort stability and do the sort in two passes:

>>> lot = [('hello', 25), ('hell', 4), ('bell', 4)]
>>> lot.sort(key=lambda r: r[0])
>>> lot.sort(key=lambda r: r[1], reverse=True)
>>> lot
[('hello', 25), ('bell', 4), ('hell', 4)]

You can also do this with sorted():

>>> lot = [('hello', 25), ('hell', 4), ('bell', 4)]
>>> sorted(sorted(lot, key=lambda r: r[0]), key=lambda r: r[1], reverse=True)
[('hello', 25), ('bell', 4), ('hell', 4)]

This is the technique recommended in Python's Sorting Howto guide.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
1

You can do the transformation within the key argument to sorted to achieve the ordering you want.

x = [('hello',25),('hell',4),('bell',4)]

sorted(x, key = lambda tup: (-tup[1], tup[0]))
Out[15]: [('hello', 25), ('bell', 4), ('hell', 4)]
roippi
  • 25,533
  • 4
  • 48
  • 73
  • 1
    While this works in this case, it isn't a general purpose solution that applies well to other cases. (for example, you can't use the technique for sort strings descending; it only works for the numbers). – Raymond Hettinger Sep 04 '14 at 03:19