1

I have the below list of tuple :

[(6,7),(0,1),(2,4),(3,5),(2,3)]

I have to first sort the tuple by their first element then if the first element is same i have to sort by the second element in descending order.

So the output should be : [(0, 1), (2, 4), (2, 3), (3, 5), (6, 7)]

I tried the below code for double sort:

from operator import itemgetter
intervals = [(6,7),(0,1),(2,4),(3,5),(2,3)]
sorted_intervals = sorted(sorted(intervals,key=itemgetter(0)),key=itemgetter(1),reverse=True)
print (sorted_intervals)

But it produces output like :

[(6, 7), (3, 5), (2, 4), (2, 3), (0, 1)]

which is not what I expect.

Can anyone give any clue how to solve this?

Frank T
  • 8,268
  • 8
  • 50
  • 67
Subhayan Bhattacharya
  • 5,407
  • 7
  • 42
  • 60

1 Answers1

-2

you can achieve it by give negative value of second element

  data = [(6,7),(0,1),(2,4),(3,5),(2,3)]
  print sorted(data, key=lambda x: (x[0],-x[1]))

output:

[(0, 1), (2, 4), (2, 3), (3, 5), (6, 7)]
galaxyan
  • 5,944
  • 2
  • 19
  • 43