-1

I have a python list as:

arr = [('f', 1), ('g', 2), ('h', 3), ('a', 1), ('j', 1), ('o', 1), ('v', 2)]

I want to sort this list in this way:

arr = [('h', 3), ('g', 2), ('v', 2), ('a', 1), ('f', 1), ('j', 1), ('o', 1)]

That is, first I want to sort the elements of the list depending on the 2nd index of each element. So I used:

arr.sort(reverse=True, key=lambda x: x[1])

It gives me this:

arr = [('h', 3), ('g', 2), ('v', 2), ('f', 1), ('a', 1), ('j', 1), ('o', 1)]

Now I further want to sort this list in ascending order depending on the elements in first position of each tuple, but I want to maintain the descending order of the values of second position of each tuple. My desired output is this-

arr = [('h', 3), ('g', 2), ('v', 2), ('a', 1), ('f', 1), ('j', 1), ('o', 1)]

Can I achieve this using one single sort() function? Or I need to use 2 sort() functions?

I don't want to use any module. I need to use lambda expression only.

Debtanu Gupta
  • 65
  • 1
  • 6

1 Answers1

1

Try this

arr = [('f', 1), ('g', 2), ('h', 3), ('a', 1), ('j', 1), ('o', 1), ('v', 2)]
arr.sort(key=lambda x: (-x[1], x[0]))
print(arr)

Output:

[('h', 3), ('g', 2), ('v', 2), ('a', 1), ('f', 1), ('j', 1), ('o', 1)]
Sabil
  • 3,750
  • 1
  • 5
  • 16