0

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

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)
4

2 回答 2

4

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

于 2013-08-20T10:45:54.893 回答
2

sorted返回您给它的任何内容的排序副本,在本例中是dict. 我想你想要的是这样的:

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

我不知道你为什么通过reverse=False。这是默认设置(这意味着它至少是多余的),并且意味着您希望它以相反的顺序排序。

于 2013-08-20T10:48:59.327 回答