1

I have a list name,weight,height like this:

list1 = [('jacob', 75, 180)
         ('sam', 90, 190)
         ('sara', 75, 175)
         ('bob', 60, 175)]

First I want to sort it by height(MAX to MIN) and I've done it. Then if the heights are the same, just sort those with same heights, by weight(MIN to MAX).

I get this:

list1 = [('sam', 190, 90)
         ('jacob', 180, 75)
         ('sara', 175, 75)
         ('bob', 175, 60)]

But I want this:

my_list = [('sam', 190, 90),
           ('jacob', 180, 75),
           ('bob', 175, 60),
           ('sara', 175, 75)]
MyNameIsCaleb
  • 4,409
  • 1
  • 13
  • 31
Sam
  • 379
  • 2
  • 10

1 Answers1

4

Assiming you don't actually mind about the order (for some reason you changed it in the output), you can use sorted with a key, where by using a negative sign you can force the ordering of a given list element to be ascending:

sorted(list1, key=lambda x: (-x[2], x[1]))

[('mahdi', 90, 190),
 ('amin', 75, 180),
 ('ahmad', 60, 175),
 ('mohamad', 75, 175)]

Otherwise simply rearange the tuples with a list comprehension:

[(i,k,j) for i,j,k in sorted(list1, key=lambda x: (-x[2], x[1]))]

[('mahdi', 190, 90),
 ('amin', 180, 75),
 ('ahmad', 175, 60),
 ('mohamad', 175, 75)]
yatu
  • 86,083
  • 12
  • 84
  • 139