python中的排序函数

LB4*_*B40 1 python sorting

我正在尝试根据我的标准对对象列表进行排序.

这是我的排序功能:

def sort_pots(self, pot1, pot2):
    coeff1 = ((pot1.movable + pot1.convertible) / pot1.total)
    coeff2 = ((pot2.movable + pot2.convertible) / pot2.total)

    if coeff1 > coeff2:
        return 1
    elif coeff1 == coeff2:
        return pot1.total - pot2.total
    else:
        return -1
Run Code Online (Sandbox Code Playgroud)

我想要实现的是:如果coeff1> coeff2,如果coeff1 == coeff2,则pot1在pot2之前,总数最高的那个在else之前(coeff2> coeff1),pot2在pot2之前

并且该功能似乎不起作用.我根据总数订购了一堆,但没有相同的系数.我(可转换,可移动,总计):0,0,1和更高版本0,3,4然后31,228,1584然后是1,0,1

这是pot1和pot2类定义的开始:

class Potential:
    def __init__(self,conf_opt):
        self.conf_opt = conf_opt
        self.total = 0
        self.movable = 0
        self.convertible = 0
Run Code Online (Sandbox Code Playgroud)

谢谢.

ton*_*nfa 9

以下工作如何?

def coef(pot):
    return (pot.movable + pot.convertible) / float(pot.total)

l.sort(key=lambda x: (coef(x), x.total), reverse=True)
Run Code Online (Sandbox Code Playgroud)

它甚至应该更快(关键比cmp更好).

  • 他想要降序排序,所以`reverse = True`. (2认同)