14数学院姚晓文
2016-11-18 17:54
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.name
return -1
elif self.name > s.name:
return 1
else:
return 0
l = []
L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
L1 = sorted(filter(lambda x:isinstance(x, int), L))
l.extend(L1)
L2 = sorted(filter(lambda x:isinstance(x, str), L))
l.extend(L2)
L3 = sorted(filter(lambda x:isinstance(x, Student), L))
l.extend(L3)
print l
我是这样分开分别对数字,字符串,对象进行分排序
博客展示了Python代码实现对数字、字符串和自定义对象的排序。定义了Student类,通过`__cmp__`方法实现对象比较。使用`filter`和`sorted`函数分别对列表中的数字、字符串和对象进行筛选和排序,最后合并结果。

被折叠的 条评论
为什么被折叠?



