How To Sort A Tuple Based On A Value Within The List Of Tuples
In python, I wish to sort tuples based on the value of their last element. For example, i have a tuple like the one below. tuples = [(2,3),(5,7),(4,3,1),(6,3,5),(6,2),(8,9)] which
Solution 1:
Povide list.sort
with an appropriate key function that returns the last element of a tuple:
tuples.sort(key=lambda x: x[-1])
Solution 2:
You can use:
from operator import itemgetter
tuples = sorted(tuples, key=itemgetter(-1))
The point is that we use key
as a function to map the elements on an orderable value we wish to sort on. With itemgetter(-1)
we construct a function, that for a value x
, will return x[-1]
, so the last element.
This produces:
>>>sorted(tuples, key=itemgetter(-1))
[(4, 3, 1), (6, 2), (2, 3), (6, 3, 5), (5, 7), (8, 9)]
Post a Comment for "How To Sort A Tuple Based On A Value Within The List Of Tuples"