zoukankan      html  css  js  c++  java
  • Python自定义排序

    比如自定义了一个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)
    
  • 相关阅读:
    VS2012的恢复默认窗口的基本常用设置
    在 CentOS 6.4 上安装 CloudStack 4.2
    centos7上安装mysql
    myeclipse安装aptana插件
    访问WEB-INF下的JSP (转载)
    通过字节流复制大文件内容到指定的文件
    java 通过bufferedReader和bufferedWriter 拷贝文件
    Date类获取日期的方法失效的解决办法
    java中string 类型的对象间比较的学习笔记
    ubuntu下搭建nfs服务器
  • 原文地址:https://www.cnblogs.com/zjutzz/p/9607085.html
Copyright © 2011-2022 走看看