這一段是怎么比較分數的??小白一個請教
??? def __cmp__(self, s):
??????? if self.score==s.score:
??????????? return cmp (self.name,s.name)
??????? return -cmp (self.score,s.score)
??? def __cmp__(self, s):
??????? if self.score==s.score:
??????????? return cmp (self.name,s.name)
??????? return -cmp (self.score,s.score)
2018-11-12
舉報
2018-11-13
這里用到的cmp(x, y)是Python2的一個內置函數,功能是如果x>y返回1,x<y返回-1,x==y返回0。
你貼出的代碼中是在分數相等的情況下,比較當前對象的name和s對象的name。(比較首字母的Ascii碼大小)否則就是比較兩個對象的分數,加個負號作用就是從大到小排序。
2019-07-16
sort函數是默認從低到高貌似,但是題目要求從高到低。所以在cmp (self.score,s.score)添加一個-號。以此來轉換排序,原本排在前面返回-1,但是現在是返回1,就是排在后面
2019-01-24
你把代碼這樣寫:
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 cmp(self.name,s.name)
? ? ? ? ? ??
? ? ? ? elif self.score < s.score:
? ? ? ? ? ? return 1
? ? ? ? elif self.score > s.score:
? ? ? ? ? ? return -1?
? ? ? ? ? ??
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)
這樣好理解些,給出的return -cmp(self.score,s,score)我也沒有理解是什么意思