Sorting tuples in python using a custom key

Hi: I'm trying to sort the list of tuples in my own way: For example:

lt = [(2,4), (4,5), (5,2)] 

need to sort:

 lt = [(5,2), (2,4), (4,5)] 

Rules:
* b tuple is larger than a tuple if a [1] == b [0]
* a tuple is greater than b tuple if a [0] == b [1]

I implemented the cmp function as follows:

 def tcmp(a, b): if a[1] == b[0]: return -1 elif a[0] == b[1]: return 1 else: return 0 

but sort the list:

 lt.sort(tcmp) 

lt show me:

 lt = [(2, 4), (4, 5), (5, 2)] 

What am I doing wrong?

+4
source share
6 answers

I am not sure if your comparison function is valid 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 depend on this property.

Not to mention that according to 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 greater than and less than b.

+2
source

It sounds a lot to me, you are trying to solve one of the problems of the Google Python class, which consists in sorting the list of tuples in ascending order based on their last element.

Here is how I did it:

 def sort_last(tuples): def last_value_tuple(t): return t[-1] return sorted(tuples, key=last_value_tuple) 

EDIT: I have not read all of this, and I assumed that it is based on the last element of the tuple. Well, I still stay here because it can be useful to anyone.

+11
source

You can write your own function to specify a key value for sorting.

Ref.

 def sort_last(tuples): return sorted(tuples, key=last) def last(a): return a[-1] 

tuples => last element sorted tuple

  • [(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)]
+4
source

You can also write your code using lambda

 def sort(tuples): return sorted (tuples,key=lambda last : last[-1]) 

therefore, sort ([((1, 3), (3, 2), (2, 1)]) will give [(2, 1), (3, 2), (1, 3)]

+4
source

Your order specification is incorrect 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) 
0
source

Try lt.sort(tcmp, reverse=True) .

(Although this may lead to the correct answer, other problems may arise with your comparison method)

-1
source

Source: https://habr.com/ru/post/1333664/


All Articles