0
[('sara', 75, 180), ('marko', 90, 190), ('jaimi', 75, 175), ('alex', 60, 175)]

I want to sort this list based on height and weight. The second element of each tuple is weight and the third is height.

Task: First sort by height (tall to short). If some element's height is equal sort that element with weight (slim to fat).

The output should be like this:

[('marko', 90, 190), ('sara', 75, 180), ('alex', 60, 175), ('jaimi', 75, 175)]

I still doing this code:

x=sorted(result,key=lambda x: (x[2],x[1]),reverse=True)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Welcome to Stack Overflow! Check out the [tour]. It's helpful to mention specific problems, like in this case, it looks like your code not sorting properly. – wjandrea Oct 29 '19 at 14:18

1 Answers1

3

Instead of specifying reverse=True, you can change the sign of the height to have the ordering both in descending and ascending order respectively:

sorted(result, key=lambda x: (-x[2], x[1]))
# [('marko', 90, 190), ('sara', 75, 180), ('alex', 60, 175), ('jaimi', 75, 175)]
yatu
  • 86,083
  • 12
  • 84
  • 139