Python 对多个属性进行排序

标签 python sorting

我有以下数据: unsorted data

我想按first_pass(反向)、level、cat(反向)、acc1 对这些数据进行排序。排序后应该是这样的顺序:sorted data

这是我在 Python 中的设置:

import math
from operator import attrgetter

class Problem:
    def __init__(self, num, first_pass, cat, acc1):
        self.num = num
        self.first_pass = first_pass
        self.cat = cat
        self.acc1 = acc1
    def level(self):
        return math.ceil((1-self.acc1)*10)
    def __repr__(self):
        return "<Num:%s 1stPass:%s Cat:%s Acc1:%s Level:%s>" % (self.num, self.first_pass, self.cat, self.acc1, self.level())


p = [
Problem(1,1,2,0.582),
Problem(2,1,2,0.44),
Problem(3,0,2,0.857),
Problem(4,0,2,0.707),
Problem(5,0,2,0.826),
Problem(6,0,1,0.781),
Problem(7,0,1,0.653),
Problem(8,1,2,0.492),
Problem(9,0,2,0.893),
Problem(10,0,1,0.582),
Problem(11,0,2,0.378),
Problem(12,0,2,0.515),
Problem(13,0,0,0.958),
Problem(14,0,1,0.633),
Problem(15,0,1,0.813),
Problem(16,0,2,0.793),
Problem(17,0,2,0.692)
]

# p.sort ??

这种类型排序的排序命令是什么?谢谢!

最佳答案

sort(ed) 的关键 kwarg 在这里可能最有用,并且有一个相对方便的技巧来对数值进行反向排序:

p.sort(key = lambda x: (-x.first_pass, x.level(), -x.cat, x.acc1))

关于Python 对多个属性进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33289429/

相关文章:

Python - 如何解码 JWT header ?

python - 如何获得每行打印一个单词的列表?

python - pylint:类 'message' 没有 'startswith' 成员

python - 如何在 python 中同时运行 2 个列表?

python - 如何告诉 bash 专门转义 Python 脚本中的通配符

Java:这里的返回是做什么的?

PHP按字段名对多维数组进行排序

c++ - [C++][std::sort] 它如何在 2D 容器上工作?

python - python 中链表实现的合并排序不起作用

MySQL Hibernate 对 2 列进行排序