【发布时间】:2016-08-10 05:45:39
【问题描述】:
这里我有两个列表:“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)
【问题讨论】:
标签: python arrays dictionary random