為什么這樣不行呢?求大神解答!~
class Student(object):
? ? def __init__(self, name, score):
? ? ? ? self.name = name
? ? ? ? self.score = score
? ? def __str__(self):
? ? ? ? return '(%s: %s)' % (self.name, self.score)
? ? __repr__ = __str__
? ? def __cmp__(self, s):
? ? ? ? if self.score>s.score:
? ? ? ? ? ? return 1
? ? ? ? elif self.score<s.socre:
? ? ? ? ? ? return -1
? ? ? ? else:
? ? ? ? ? ? return 0
? ? ? ??
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)
2019-04-01
你這里只比較了分數,沒有比較分數相同時的名字排序
你的完善版本應該是這樣
2020-05-06
if self.score < s.score:
? ? ? ? ? ? return 1
? ? ? ? elif self.score > s.score:
? ? ? ? ? ? return -1
? ? ? ? else:
? ? ? ? ? ? return cmp(self.name,s.name)
2019-04-16
學習了