Python - 获得两个dict列表的平均值?

时间:2016-08-10 05:45:39

标签: python arrays dictionary random

这里我有两个列表:" donlist"是一个介于$ 1和$ 100之间的随机捐赠金额列表,以及" charlist"是1到15之间的随机慈善数字列表。我使用了两个" dict""""总计"计算每个慈善机构的捐赠总额,以及" numdon"计算每个慈善机构的捐款数量。我现在必须找到每个慈善机构的平均捐款。我试过划分"总计"通过" numdon",但输出只是" 1.0"的列表。我认为这是因为该词典有慈善号码以及其中的捐款总数/数量。请帮我计算每个慈善机构的平均捐款额。谢谢!

from __future__ import division
import random
from collections import defaultdict
from pprint import pprint

counter = 0
donlist = []
charlist = []
totals = defaultdict(lambda:0)
numdon = defaultdict(lambda:0)

while counter != 100:
    d = round(random.uniform(1.00,100.00),2)
    c = random.randint(1,15)
    counter +=1
    donlist.append(d)
    donlist = [round(elem,2) for elem in donlist]
    charlist.append(c)
    totals[c] += d
    numdon[c] += 1

    if counter == 100:
        break

print('Charity \t\tDonations')
for (c,d) in zip(charlist,donlist):
    print(c,d,sep='\t\t\t')
print("\nTotal Donations per Charity:") 
pprint(totals)
print("\nNumber of Donations per Charity:")
pprint(numdon)

# The average array doesn't work; I think it's because the "totals" and "numdon" have the charity numbers in them, so it's not just two lists of floats to divide.
avg = [x/y for x,y in zip(totals,numdon)]
pprint(avg)

1 个答案:

答案 0 :(得分:3)

解决您的问题:

0

<强>原因

在dict的python列表理解中,默认迭代将在dict的键上。试试这个:

avg = [totals[i] / numdon[i] for i in numdon]