比如自定義了一個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)
