如何在python语言中进行反向排序?

时间:2013-08-20 10:40:23

标签: python

我编写了python代码,从日志中获取密钥,并通过advert_sum进行下降排序,当我调用sort函数时,

sorted(dict, cmp=lambda x,y: cmp(adver_num), reverse=False)

报告not adver_num。我该如何解决? dict[].adver_num?我尝试了一些方法,但它仍然失败了。

import re
dict={}
class log:
    def __init__(self,query_num, adver_num):
        self.query_num = query_num
        self.adver_num = adver_num
f = open('result.txt','w')

for line in open("test.log"):
   count_result = 0
   query_num = 0
   match=re.search('.*qry=(.*?)qi.*rc=(.*?)dis',line).groups()
   counts=match[1].split('|')
   for count in counts:
      count_result += int(count)
   if match[0].strip():
     if not dict.has_key(match[0]):
        dict[match[0]] = log(1,count_result)
     else:
        query_num = dict[match[0]].query_num+1;
        count_result = dict[match[0]].adver_num+count_result;
        dict[match[0]] = log(query_num,count_result)
     #f.write("%s\t%s\n"%(match[0],count_result))

sorted(dict,cmp=lambda x,y:cmp(adver_num),reverse=False)
for i in dict.keys():
    f.write("%s\t%s\t%s\n"%(i,dict[i].query_num,dict[i].adver_num)

2 个答案:

答案 0 :(得分:4)

首先,dict无法排序,您需要使用list。其次,sorted函数不会修改其参数,而是返回一个新列表。尝试在任何字典上调用sorted,您将得到一个按键的排序列表作为返回值。

答案 1 :(得分:2)

sorted返回您提供的任何内容的排序副本,在本例中是dict中的键列表。我想你想要的是:

s = sorted(dict.iteritems(), key=lambda x: x[1].adver_num, reverse=True)
for (i, _) in s:
    …

我不确定你为什么通过reverse=False。这是默认值(这意味着它至少是冗余的),并且意味着希望它以相反的顺序排序。