-4
   b= sorted(calls,key=lambda x:x[0]-x[1] )

In case the subtraction is equal the list should be sorted on the basis of the 2nd Element

Ankit Agrawal
  • 101
  • 1
  • 7

1 Answers1

1

sorted(calls, key=lambda x: sum(x))

I don't believe there is a way to specify a secondary sort parameter as you requested, so you'll have to sort your collection twice. Sort it first by the value of the second element, then sort again by the sum. Elements which have the same sum will retain the ordering from the first sort.

EDIT:

There is a way to specify multiple sort keys! Your lambda function can return a tuple of values. The first item in the tuple is the primary sort key, the second item is the secondary key, and so on:

sorted(calls, key=lambda x: (sum(x), x[1]))

Thanks to @tzot's answer to this question !

Community
  • 1
  • 1
John Gordon
  • 29,573
  • 7
  • 33
  • 58