Home > Enterprise >  How do I sort lists by two different values within that list?
How do I sort lists by two different values within that list?

Time:02-01

I have a list that is of the following form:

my_list= [['A',(3,4)],['A2',(6,11)],['U1',(2,9)],['P9',(1,9)], ['X',(10,4)]...]

I need to sort the letter/number combinations based on the list that corresponds with them, (1,2,3,4) for example.

The second number in the list needs to be in descending order. Then, the first number in that list needs to be in descending order. The last number takes priority over the first number.

These numbers correspond to the location of these values on an image. I am attempting to sort these by the way they appear on the image (top to bottom, left to right).

The correct order for the above list would be: ['A2',(6,11)], ['U1',(2,9)],['P9',(1,9)], ['X',(10,4)], [['A',(3,4)]

To be frank, I do not know where to start with this. Could someone please explain how to properly write this in Python?

CodePudding user response:

You can pass a key function to list.sort to specify what to sort by.

my_list.sort(key=lambda x: (-x[1][1], -x[1][0]))

CodePudding user response:

In general: to sort by multiple keys, you need a stable sort (and Python's sort is stable) and then you can do it in steps from the least important key to the primary key. In your case by the first number descending and then by the second number also descending:

s0 = [['A',(3,4)],['A2',(6,11)],['U1',(2,9)],['P9',(1,9)], ['X',(10,4)]]

s1 = sorted(s0, key = lambda x: x[1][0], reverse=True)
print(s1) # intermediate result
s2 = sorted(s1, key = lambda x: x[1][1], reverse=True)
print(s2) # final result
  • Related