如果List中元素类型不同,如何排序?
注意: 如果list不仅仅包含 Student 类,则 __cmp__ 可能会报错:
L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello'] print sorted(L)
请思考如何解决。
注意: 如果list不仅仅包含 Student 类,则 __cmp__ 可能会报错:
L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello'] print sorted(L)
请思考如何解决。
2018-10-07
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 isinstance(s,Student):
if self.score>s.score:
return -1
elif self.score<s.score:
return 1
else :
return cmp(self.name,s.name)
elif isinstance(s,int):
if self.score>s :
return -1
elif self.score<s :
return 1
else :
return 0
elif isinstance(s,str):
return cmp(self.name,s)
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)
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 isinstance(s,Student):
if self.score < s.score:
return 1
elif self.score > s.score:
return -1
else:
if self.name < s.name:
return -1
elif self.name > s.name:
return 1
else:
return 0
if isinstance(s,int):
if self.score < s:
return 1
elif self.score > s:
return -1
else:
return 0
if isinstance(s,str):
if self.name < s:
return 1
elif self.name > s:
return -1
else:
return 0
L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
print sorted(L)
不晓得这样行不行
举报