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)]
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)]
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.
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)]