python - 根据键对字典中的值取平均值

标签 python dictionary

我是 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

我还必须计算键的数量,以便得出平均值。虽然看起来工作量很大 - 我不确定是否有更优雅的方法来完成此任务。

谢谢。

最佳答案

您可以使用 collections.defaultdict创建具有唯一键和值列表的字典:

>>> l=[(3, '655'),(3, '645'),(3, '641'),(4, '602'),(4, '674'),(4, '620')]
>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> 
>>> for i,j in l:
...    d[i].append(int(j))
... 
>>> d
defaultdict(<type 'list'>, {3: [655, 645, 641], 4: [602, 674, 620]})

然后使用列表理解来创建预期的对:

>>> [(i,sum(j)/len(j)) for i,j in d.items()]
[(3, 647), (4, 632)]

在您的代码中您可以:

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]
        d[month].append(int(avg))

     print [(i,sum(j)/len(j)) for i,j in d.items()]

关于python - 根据键对字典中的值取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29565452/

相关文章:

python - 替换字典中所有字典中的冗余键名称

java - (Hash-)Map 有条目,get 传递 null

python - 如何为没有字段的模型制作 Django 固定装置?

python - 如何获取当前可用于 Matplotlib 的所有字体的列表?

python - 在 Dreamhost 上调试 Django/Python

python - OKTA Sso python

python - 根据字符串拆分将列表拆分为子列表

python - 在 python 2.7 [windows - 64 位] 上安装 xlwt 模块

c - 如何判断字典中是否包含某个值?

python - 使用外部文件定义字典键的值列表