如何在python中存储多个值?

时间:2013-08-20 08:30:24

标签: python dictionary

我编写了一个python代码,用于计算查询数量和日志中的广告数量。

例如(google, 16, 35)其中google表示查询,16表示查询号,35表示广告编号。

我考虑过定义两个词典,一个词典是商店query->query_number,另一个是query->advertisement,然后加入这两个词典。

但它似乎过于复杂,是否可以将query, query_num, advertisement_num存储在一个字典中?

if match[0].strip():
     if not dict.has_key(match[0]):
        dict[match[0]] = 1
     else:
        dict[match[0]] +=1

此代码用于计算queryNum,但我还是要存储adver_count。我该怎么办?

我已经使用class来存储query_num和adver_num.Here是我的代码。我如何根据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')

def sort_by_value(d):
   return sorted(d.items(), lambda x, y: cmp(x[1], y[1]), reverse=True)

for line in open("test.log"):
   count_result = 0
   query_num = 0
   match=re.search('.*qry=(.*?)qid0.*rc=(.*?)discount',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))

sort_by_value(dict)

for i in dict.keys():
    f.write("%s\t%s\t%s\n"%(i,dict[i].query_num,dict[i].adver_num))

4 个答案:

答案 0 :(得分:1)

您只能使用一个字典,query作为键,而元组(query_num, advertisement_num)作为值。

代码示例:

计算queryNum时,

if match[0].strip():
    if not dict.has_key(match[0]):
        dict[match[0]] = (1,0)
    else:
        qnum, adnum = dict[match[0]]
        dict[match[0]] = (qnum + 1, adnum)

答案 1 :(得分:0)

您可以为自己创建课程:

class YourClass:
    def __init__(self, query, query_num, adver_num):
        self.query = query
        self.query_num = query_num
        self.adver_num = adver_num

谢谢你可以像:

一样处理它
your_dictionary['google'] = YourClass('google', 16, 35)

并访问以下值:

print your_dictionary['google'].query, your_dictionary['google'].query_num, your_dictionary['google'].adver_num

答案 2 :(得分:0)

是的,你可以。使用query作为键,您只需使用元组作为dict的值:

d = {"google": (16, 35)}

您甚至可以使用字典作为值:

d = {"google": {"query number": 16, "advertisement number": 35}}

答案 3 :(得分:-1)

您可以使用itertools链将查询集保存到同一个列表中,如下所示;

#Import itertools
from itertools import chain
# use itertools chain to store your querysets into a list/variable like "store" 
store = list(chain(query_num, advertisement_num))