比如自定义了一个class,并且实例化了这个类的很多个实例,并且组成一个数组。这个数组要排序,是通过这个class的某个字段来排序的。怎么排序呢?
有两种做法:
第一种是定义
__cmp__( )
方法;第二种是在
sorted( )
函数中为key
指定一个lambda函数,lambda函数用来排序。
举例(这里都是降序排序,所以指定了reserved=True,可以忽略):
第一种方法:
class BBox(object):
def __init__(self, name, score, x1, y1, x2, y2):
self.name = name
self.score = score
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def __str__(self):
ret_str = 'name:{:s}, score:{:f}, x1={:d},y1={:d},x2={:d},y2={:d}'.format(
self.name, self.score, self.x1, self.y1, self.x2, self.y2
)
return ret_str
def __cmp__(self, other):
return cmp(self.score, other.score)
det test():
x1 = 1
y1 = 3
x2 = 6
y2 = 9
b1 = BBox('box1', 0.5, x1, y1, x2, y2)
b2 = BBox('box2', 0.7, x1, y1, x2, y2)
b3 = BBox('box3', 0.3, x1, y1, x2, y2)
box_lst = [b1, b2, b3]
box_lst = sorted(box_lst, reverse=True)
for box in box_lst:
print(box)
第二种方法:
class BBox(object):
def __init__(self, name, score, x1, y1, x2, y2):
self.name = name
self.score = score
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def __str__(self):
ret_str = 'name:{:s}, score:{:f}, x1={:d},y1={:d},x2={:d},y2={:d}'.format(
self.name, self.score, self.x1, self.y1, self.x2, self.y2
)
return ret_str
det test():
x1 = 1
y1 = 3
x2 = 6
y2 = 9
b1 = BBox('box1', 0.5, x1, y1, x2, y2)
b2 = BBox('box2', 0.7, x1, y1, x2, y2)
b3 = BBox('box3', 0.3, x1, y1, x2, y2)
box_lst = [b1, b2, b3]
box_lst = sorted(box_lst, key=lambda box: box.score, reserved=True)
for box in box_lst:
print(box)