首先我创建了一个这样的类
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
然后我有一个Student对象列表
L = [(Student: Tim, 99), (Student: Alice, 99), (Student: Bob, 88)]
如何按照得分的降序对此列表进行排序,然后如果两个得分相同,则按名称按升序字母顺序对其进行排序
我尝试使用attrgetter
,但我总是得到与上面的L
预期输出
L = [ (Student: Alice, 99),(Student: Tim, 99), (Student: Bob, 88)]
答案 0 :(得分:0)
您可以在已排序的方法中添加键arg
sortedL = sorted(L, key=lambda student: student.name)
答案 1 :(得分:0)
定义一个可用作排序关键参数的函数。您可以定义该函数,以便指定它的排序方式
>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
答案 2 :(得分:-1)
默认情况下,sorted
使用您要比较的对象的__cmp__
方法。
class Student(object):
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __cmp__(self, other):
if self.grade < other.grade:
return +1
elif self.grade > other.grade:
return -1
else:
return cmp(self.name, other.name)
def __repr__(self):
return "({}, {})".format(self.name, self.grade)
s1 = Student('Tim', 99, 12)
s2 = Student('Alice', 99, 12)
s3 = Student('Bob', 88, 13)
sorted([s1, s2, s3])