Home > Software design >  Sort a list of lists using descending order, and then if there is a tie breaker, use descending orde
Sort a list of lists using descending order, and then if there is a tie breaker, use descending orde

Time:02-26

master_list = [["Hi", 2.00],["Hey", 6.01],["Hello", 9.56], ["How", 6.01]]
master_list.sort(key=lambda x: -(x[1], -x[0]))

I tried using this function to sort the master_list in descending order by the number, and if there is a tie, descending order by the string. However, I get the error "TypeError: bad operand type for unary -: 'str' I don't know what I am doing wrong to get this error. How do I sort the list?

CodePudding user response:

It is because you are applying a negation (-) on a tuple a string. Using sorted function, you can use reverse=True to sort the array in descending order.

sorted(master_list, key=lambda x: (x[1], x[0]), reverse=True) 
  • Related