9
I have a list of fashion tuples:
[(0, 1), (2, 3), (4, -5), (6, -3)]
I want to sort that list by the second value of each tuple (i.e., in case we would [(4, -5), (6, -3), (0, 1), (2, 3)]
. How to do this?
9
I have a list of fashion tuples:
[(0, 1), (2, 3), (4, -5), (6, -3)]
I want to sort that list by the second value of each tuple (i.e., in case we would [(4, -5), (6, -3), (0, 1), (2, 3)]
. How to do this?
12
The simplest way is to use key
in the call to method sort
of the list:
data = [(0, 1), (2, 3), (4, -5), (6, -3)]
data.sort(key=lambda x: x[1])
>>> data
[(4, -5), (6, -3), (0, 1), (2, 3)]
Thus, the element 1
of each tuple will be the sorting key. Another option considered fastest is to use the function itemgetter
library operator
.
Browser other questions tagged python tuple classification
You are not signed in. Login or sign up in order to post.