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!
Since the first value in the tuple is a number, you can negate that instead and give sorted the reverse=True flag; this will give the desired effect of sorting the numbers in numerical order (reverse sorting negated numbers gives the same result as sorting the original numbers) and the strings in reverse-alphabetical order. For example:
h = [(1, 'ghi'), (2, 'abc'), (2, 'def')]
print(sorted(h, key=lambda tup: (-tup[0], tup[1]), reverse=True))
Output:
[(1, 'ghi'), (2, 'def'), (2, 'abc')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With