python字典求平均值_python – 根据键对字典中的值求平均值

我是

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

我还必须保持按键数量的计数,这样才能产生平均值.看起来好像很多工作 – 我不确定是否有更优雅的方法来实现这一目标.

谢谢.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值