I need to complete a task where I am given a list of names and grades for each name and I need to sort these out by highest to lowest grade. However if two names have the same grades then sort those names out in alphabetical order. This is the problem I am presented with. I am required to keep the sort function on one line.
a = [('Tim Jones', 54), ('Anna Smith', 56), ('Barry Thomas', 88)]
sum(sorted(a,key=lambda x: x[1]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
Any idea on how this can be resolved? I've tried to work it out for many days now.
UPDATED
Ok thanks for helping me work out that one, however there is another scenario where I need to resolve as well.
a = [('Tim Jones', 'C'), ('Anna Smith', 'B'), ('Barry Thomas', 'A')]
sorted(a,key=lambda x: -x[1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: bad operand type for unary -: 'str'
So this is the current situation basically all I need to do now is organise the list so then it goes from highest grade to lowest grade.
Let's note that
sorted()
will return a copy of your original list, but sorted:Python itself will fail when attempting to sum these three tuples, because it doesn't really have any clear meaning.