Home > Enterprise >  Sort the list and element of the list is tuple but I have sort the array with both both the element
Sort the list and element of the list is tuple but I have sort the array with both both the element

Time:08-31

List

[(3,4),(4,5),(4,6)] 

I want to sort the list with first element as max ie 4 but sort the second element with min first ie 5. Output be like

[(4,5),(4,6),(3,4)]

CodePudding user response:

This will do it:

l = [(3,4),(4,5),(4,6)]

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

print(l)

Output:

[(4, 5), (4, 6), (3, 4)]

CodePudding user response:

Try this:

lst = [(3,4),(4,6),(4,5)]

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

print(lst)

Output:

[(4, 5), (4, 6), (3, 4)]
  • Related