python如何实现对包含对象,数字,字母的排序
注意: 如果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)
2016-11-18
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 < s.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
我是这样分开分别对数字,字符串,对象进行分排序
举报