-1

I have the below list.

[[1, [400, 'London']],
 [1, [420, 'Paris']],
 [2, [430, 'London']],
 [2, [440, 'Paris']],
 [3, [550, 'Mumbai']],
 [3, [460, 'Paris']],
 [4, [560, 'Mumbai']],
 [4, [510, 'Dubai']],
 [5, [525, 'Dubai']],
 [5, [520, 'London']],
 [6, [550, 'London']],
 [6, [520, 'Paris']],
 [7, [580, 'London']],
 [7, [540, 'Paris']]]

I wanted to sort the list in descending order based on the first value inside the nested lists. For example,

[[1, [420, 'Paris']]],
 [1, [400, 'London']],
 [2, [440, 'Paris']],
 [2, [430, 'London']]]

and so on..

1 Answers1

5

Assuming l the input, use sorted with the key parameter:

l2 = sorted(l, key=lambda x: (x[0], -x[1][0]))

Inverting the second number sorts it by decreasing value.

output:

[[1, [420, 'Paris']],
 [1, [400, 'London']],
 [2, [440, 'Paris']],
 [2, [430, 'London']],
 [3, [550, 'Mumbai']],
 [3, [460, 'Paris']],
 [4, [560, 'Mumbai']],
 [4, [510, 'Dubai']],
 [5, [525, 'Dubai']],
 [5, [520, 'London']],
 [6, [550, 'London']],
 [6, [520, 'Paris']],
 [7, [580, 'London']],
 [7, [540, 'Paris']]]
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
mozway
  • 194,879
  • 13
  • 39
  • 75