java按属性排序_按多个属性对列表进行排序?

这是一种方法:你基本上重写你的排序函数来获取排序函数列表,每个排序函数比较你想要测试的属性,在每个排序测试中,你看,看看cmp函数是否返回非零返回如果是这样打破并发送返回值 . 您可以通过调用Lambda列表函数的Lambda来调用它 .

它的优点是它可以单独传递数据,而不是像其他方法那样的前一种数据 . 另一件事是它排序到位,而排序似乎复制 .

我用它来编写一个排名函数,它对每个对象在一个组中的类列表进行排序,并且有一个得分函数,但是你可以添加任何属性列表 . 注意非lambda式,虽然hackish使用lambda来调用setter . 排名部分不适用于列表数组,但排序将 .

#First, here's a pure list version

my_sortLambdaLst = [lambda x,y:cmp(x[0], y[0]), lambda x,y:cmp(x[1], y[1])]

def multi_attribute_sort(x,y):

r = 0

for l in my_sortLambdaLst:

r = l(x,y)

if r!=0: return r #keep looping till you see a difference

return r

Lst = [(4, 2.0), (4, 0.01), (4, 0.9), (4, 0.999),(4, 0.2), (1, 2.0), (1, 0.01), (1, 0.9), (1, 0.999), (1, 0.2) ]

Lst.sort(lambda x,y:multi_attribute_sort(x,y)) #The Lambda of the Lambda

for rec in Lst: print str(rec)

这是一种对对象列表进行排名的方法

class probe:

def __init__(self, group, score):

self.group = group

self.score = score

self.rank =-1

def set_rank(self, r):

self.rank = r

def __str__(self):

return '\t'.join([str(self.group), str(self.score), str(self.rank)])

def RankLst(inLst, group_lambda= lambda x:x.group, sortLambdaLst = [lambda x,y:cmp(x.group, y.group), lambda x,y:cmp(x.score, y.score)], SetRank_Lambda = lambda x, rank:x.set_rank(rank)):

#Inner function is the only way (I could think of) to pass the sortLambdaLst into a sort function

def multi_attribute_sort(x,y):

r = 0

for l in sortLambdaLst:

r = l(x,y)

if r!=0: return r #keep looping till you see a difference

return r

inLst.sort(lambda x,y:multi_attribute_sort(x,y))

#Now Rank your probes

rank = 0

last_group = group_lambda(inLst[0])

for i in range(len(inLst)):

rec = inLst[i]

group = group_lambda(rec)

if last_group == group:

rank+=1

else:

rank=1

last_group = group

SetRank_Lambda(inLst[i], rank) #This is pure evil!! The lambda purists are gnashing their teeth

Lst = [probe(4, 2.0), probe(4, 0.01), probe(4, 0.9), probe(4, 0.999), probe(4, 0.2), probe(1, 2.0), probe(1, 0.01), probe(1, 0.9), probe(1, 0.999), probe(1, 0.2) ]

RankLst(Lst, group_lambda= lambda x:x.group, sortLambdaLst = [lambda x,y:cmp(x.group, y.group), lambda x,y:cmp(x.score, y.score)], SetRank_Lambda = lambda x, rank:x.set_rank(rank))

print '\t'.join(['group', 'score', 'rank'])

for r in Lst: print r

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值