gpt4 book ai didi

Python 对多个属性进行排序

转载 作者:行者123 更新时间:2023-11-28 22:40:43 26 4
gpt4 key购买 nike

我有以下数据: 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com