Python按多个属性排序

时间:2015-10-22 19:46:06

标签: 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命令是什么?谢谢!

3 个答案:

答案 0 :(得分:2)

使用sorted。使用sorted的{​​{3}}很好。试试这个:

from operator import attrgetter

s = sorted(p, key=attrgetter('acc1'))
s = sorted(s, key=attrgetter('cat'), reverse=True)
s = sorted(s, key=lambda problem: problem.level())
s = sorted(s, key=attrgetter('first_pass'), reverse=True)

它将按first_pass(反向),level,cat(反向),acc1对数据进行排序。但你必须反过来做。以下是s的输出:

[<Num:1 1stPass:1 Cat:2 Acc1:0.582 Level:5>,
 <Num:2 1stPass:1 Cat:2 Acc1:0.44 Level:6>,
 <Num:8 1stPass:1 Cat:2 Acc1:0.492 Level:6>,
 <Num:13 1stPass:0 Cat:0 Acc1:0.958 Level:1>,
 <Num:5 1stPass:0 Cat:2 Acc1:0.826 Level:2>,
 <Num:3 1stPass:0 Cat:2 Acc1:0.857 Level:2>,
 <Num:9 1stPass:0 Cat:2 Acc1:0.893 Level:2>,
 <Num:15 1stPass:0 Cat:1 Acc1:0.813 Level:2>,
 <Num:4 1stPass:0 Cat:2 Acc1:0.707 Level:3>,
 <Num:16 1stPass:0 Cat:2 Acc1:0.793 Level:3>,
 <Num:6 1stPass:0 Cat:1 Acc1:0.781 Level:3>,
 <Num:17 1stPass:0 Cat:2 Acc1:0.692 Level:4>,
 <Num:14 1stPass:0 Cat:1 Acc1:0.633 Level:4>,
 <Num:7 1stPass:0 Cat:1 Acc1:0.653 Level:4>,
 <Num:12 1stPass:0 Cat:2 Acc1:0.515 Level:5>,
 <Num:10 1stPass:0 Cat:1 Acc1:0.582 Level:5>,
 <Num:11 1stPass:0 Cat:2 Acc1:0.378 Level:7>]

答案 1 :(得分:1)

Python的sorted函数使用稳定排序,因此如果要对多个字段进行排序,可以使用多个排序来执行此操作。例如,如果有一个人员列表,并且您希望按姓氏排序,并使用名字作为辅助排序,则首先按名字排序。

由于我碰巧实际上打开了这个文件,你可以试试这个:

def sorted_by(collection, lambdas, reverse):
    for l in lambdas:
        collection = sorted(collection, key=l, reverse=reverse)
    return collection

其中lambdas是排序函数列表。

答案 2 :(得分:1)

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

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