I have a list like this and I want to sort it by the second value.
lst = [[x, 5], [y, 1], [z, 6]]
like this
lst = [[z,6],[x,5],[y,1]]
CodePudding user response:
You can use sorted
sorted(lst, key= lambda elem : elem[1], reverse=True)
From the doc itself:
sorted
: Returns a new sorted list from the items in iterable.
Has two optional arguments which must be specified as keyword arguments.
key
: specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=<lambda_function>
). The default value is None (compare the elements directly).
reverse
: is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
CodePudding user response:
There are two simplest ways to achieve that:
- In-place operation with a
list.sort()
method:
lst.sort(key=lambda l: l[1], reverse=True)
- or with a
sorted()
built-in operation that builds(*) a new sorted list from an iterable:
sorted(lst, key=lambda l: l[1], reverse=True)
The reverse=True
parameter is necessary for this case to achieve descending order (the default value for this parameter for both functions is equal False
, which ends up with an ascending order).
(*) That means you can assign the copy of the list to the variable for future use (caution: both lists will get sorted anyway):
new_lst = sorted(lst, key=lambda l: l[1], reverse=True)
To speed up the process, you can use an operator.itemgetter()
method. You can execute it by importing the method (from operator import itemgetter
) and changing the value for the key
parameter:
lst.sort(key=itemgetter(1), reverse=True)
sorted(lst, key=itemgetter(1), reverse=True)
CodePudding user response:
sorted returns a new list. If you want to sort the list in place, then you can use list.sort().
lst.sort(reverse=True, key= lambda elem : elem[1])