unsupported operand type(s) for +: 'int' and 'tuple'

最后都变了- 提交于 2019-12-11 07:43:53

问题


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.


回答1:


Let's note that sorted() will return a copy of your original list, but sorted:

>>> a = [('Tim Jones', 54), ('Anna Smith', 56), ('Barry Thomas', 88)]
>>> sorted(a,key=lambda x: x[1])
[('Tim Jones', 54), ('Anna Smith', 56), ('Barry Thomas', 88)]

Python itself will fail when attempting to sum these three tuples, because it doesn't really have any clear meaning.

('Tim Jones', 54)
('Anna Smith', 56)
('Barry Thomas', 88)



回答2:


The sorted() function return a tuple list. So you can't sum them up because sum() suppose to receive a sequence of numerics.

The second one is because you have a minus (-) before the x[1] while x[1] is a string. You can't have a negative string.

>>> a = [('Tim Jones', 'C'), ('Anna Smith', 'B'), ('Barry Thomas', 'A')]
>>> sorted(a,key=lambda x: x[1])

If you wanna sort those names out in alphabetical order when grades are the same, then use tuple (x[1],x[0]) as the sorted key.

>>> a = [('Tim Jones', 54), ('Anna Smith', 56), ('Barry Thomas', 88),('Array Thomas', 88)]
>>> sorted(a,key=lambda x: (x[1],x[0]))
[('Tim Jones', 54), ('Anna Smith', 56), ('Array Thomas', 88), ('Barry Thomas', 88)]


来源:https://stackoverflow.com/questions/27028833/unsupported-operand-types-for-int-and-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!