繁体   English   中英

Python-获取两个字典列表的平均值?

[英]Python - getting the average of two dict lists?

在这里,我有两个列表:“ donlist”是一个介于$ 1和$ 100之间的随机捐赠金额列表,“ charlist”是一个介于1和15之间的随机慈善编号列表。我使用了两个“ dict”:“ totals”计算每个慈善机构的捐款总额,“ 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)

解决您的问题:

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

原因

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

l = {1: 'a', 2: 'b'}
for i in l:
    print(i) 
# output:
# 1
# 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM