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

2024-09-27 09:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里我有两个列表:“donlist”是一个1到100美元之间的随机捐赠金额列表,“charlist”是一个1到15之间的随机慈善数字列表。我用了两个“dict”:“totals”来计算每个慈善机构的捐款总额,用“numdon”来计算每个慈善机构的捐款数量。我现在要找出每个慈善机构的平均捐款额。我试着用“总数”除以“numdon”,但结果只是一个“1.0”的列表。我想这是因为dict中有慈善数字以及捐赠的总数。请帮我计算一下每个慈善机构的平均捐款额。谢谢您!你知道吗

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)

Tags: infromimport列表forcounterrandompprint
1条回答
网友
1楼 · 发布于 2024-09-27 09:26:13

解决您的问题:

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

原因:

在dict的python列表理解中,默认迭代将位于dict的键上。请尝试以下操作:

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

相关问题 更多 >

    热门问题