我是
Python新手,我有一组如下的值:
(3, '655')
(3, '645')
(3, '641')
(4, '602')
(4, '674')
(4, '620')
这是使用以下代码(python 2.6)从CSV文件生成的:
import csv
import time
with open('file.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
date = time.strptime(row[3], "%a %b %d %H:%M:%S %Z %Y")
data = date, row[5]
month = data[0][1]
avg = data[1]
monthAvg = month, avg
print monthAvg
我想要做的是根据键获得平均值:
(3, 647)
(4, 632)
我最初的想法是创建一个新词典.
loop through the original dictionary
if the key does not exist
add the key and value to the new dictionary
else
sum the value to the existing value in the new dictionary
我还必须保持按键数量的计数,这样才能产生平均值.看起来好像很多工作 – 我不确定是否有更优雅的方法来实现这一目标.
谢谢.