I have reviewed several questions so far about this topic, and I can't seem to find an answer. My objective is to sort a Python list of tuples by two criteria. The following code throws the error in the question title (Python3):
h = [(1, 'ghi'), (2, 'abc'), (2, 'def')]
print(sorted(h, key=lambda tup: (tup[0], -tup[1])))
The idea here is to first sort by the integer in the tuple, and then sort the list by reverse-alphabetical order of the string in the tuple. I am looking for output like the below. This is also what I would expect the above line to print, but instead I get TypeError: Bad Operand Type for Unary -: 'str':
[(1, 'ghi'), (2, 'def'), (2, 'abc')]
I understand that I can write a custom comparator to achieve this, but several answers on this site seem to suggest that this sorting is possible by passing the correct lambda function. What am I doing wrong? Is this possible? Thanks!