Reputation: 49
Currently, I have a list of lists called result
which will contain values like this, for example:
result[1] = [John, 0.32]
result[2] = [Mikey, 1.90]
result[3] = [Sarah, 1.31]
result[4] = [Nancy, 0.49]
result[5] = [Billy, 0.13]
I want to however, sort this in descending order by the number which is held in the index space [1]. So the system will return the values in that order. Would I just have to use the sorted()
function and call up the index where the value is held? I do not need to resort the list is it is necessary, i will just need to output the values in descending order.
How would I go about doing this exactly?
Upvotes: 1
Views: 49
Reputation: 239443
Use the key
parameter in the sorted
function.
sorted(result, key = lambda x:x[1], reverse = True)
The reverse = True
makes sure that the items are sorted in the descending order. The important thing to be noted here is the key
parameter.
key = lambda x:x[1]
We pass a lambda function to the key
parameter, which accepts one parameter. sorted
picks each element from result
and pass that to the key
function. In our case it is the tuples. The key
function returns the second item in the tuples. So, the second item in the tuple will be used as the value of the tuple itself, while sorting. It means that when we comapre [John, 0.32]
and [Mikey, 1.90]
, we will be actually comparing 0.32
and 1.90
only.
sorted
doesn't change the actual list, but creates a new sorted list. But, if you want to sort the list itself, then you can use list.sort
method, like this
result.sort(key = lambda x:x[1], reverse = True)
Upvotes: 5
Reputation: 32189
You can do that using sorted
:
new_list = sorted(old_list, key=lambda x: x[1], reverse=True)
or using sort
:
old_list.sort(key=lambda x: x[1], reverse=True)
Upvotes: 0