问题描述
我需要完成一个任务,为我提供每个名称的名称和等级列表,并且需要按最高到最低等级对它们进行排序.但是,如果两个名称具有相同的等级,则请按字母顺序对这些名称进行排序.这是我遇到的问题.我需要将排序功能保持在一行上.
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.
已更新
好,谢谢您帮助我解决了这个问题,但是在另一种情况下,我也需要解决.
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.
推荐答案
请注意,sorted()
将返回原始列表的副本,但排序如下:
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本身将失败,因为它实际上没有任何明确的含义.
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)
这篇关于+不支持的操作数类型:"int"和"tuple"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!