Sorting Tuples In Python With A Custom Key
Solution 1:
Sounds a lot to me you are trying to solve one of the Google's Python class problems, which is to sort a list of tuples in increasing order based on their last element.
This how I did it:
defsort_last(tuples):
deflast_value_tuple(t):
return t[-1]
returnsorted(tuples, key=last_value_tuple)
EDIT: I didn't read the whole thing, and I assumed it was based on the last element of the tuple. Well, still I'm going to leave it here because it can be useful to anyone.
Solution 2:
You could also write your code using lambda
defsort(tuples):
returnsorted (tuples,key=lambda last : last[-1])
so sort([(1, 3), (3, 2), (2, 1)]) would yield [(2, 1), (3, 2), (1, 3)]
Solution 3:
You can write your own custom key function to specify the key value for sorting.
Ex.
defsort_last(tuples):
returnsorted(tuples, key=last)
deflast(a):
return a[-1]
tuples => sorted tuple by last element
[(1, 3), (3, 2), (2, 1)]
=>[(2, 1), (3, 2), (1, 3)]
[(1, 7), (1, 3), (3, 4, 5), (2, 2)]
=>[(2, 2), (1, 3), (3, 4, 5), (1, 7)]
Solution 4:
I'm not sure your comparison function is a valid one in a mathematical sense, i.e. transitive. Given a, b, c
a comparison function saying that a > b
and b > c
implies that a > c
. Sorting procedures rely on this property.
Not to mention that by your rules, for a = [1, 2]
and b = [2, 1]
you have both a[1] == b[0]
and a[0] == b[1]
which means that a is both greater and smaller than b.
Solution 5:
Your ordering specification is wrong because it is not transitive.
Transitivity means that if a < b
and b < c
, then a < c
. However, in your case:
(1,2) < (2,3)
(2,3) < (3,1)
(3,1) < (1,2)
Post a Comment for "Sorting Tuples In Python With A Custom Key"