【问题标题】:Python - getting the average of two dict lists?Python - 获得两个字典列表的平均值?
【发布时间】: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


    【解决方案1】:

    解决您的问题:

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

    原因

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

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

    【讨论】:

    • 成功了,谢谢!对于每笔捐款,我还必须打印它是否高于、低于或等于平均捐款金额。你知道一个简单的方法来做到这一点吗?如果太费时间也没关系。谢谢!
    • 既然你已经有了donlistavg,你可以简单地循环donlist[(ch,compare(don, avg[ch])) for ch, don in zip(charlist,donlist)],其中 compare 是一个你应该实现比较捐赠金额和平均值并返回的函数高于、低于或等于。
    • 非常感谢!我现在将努力将其添加到我的代码中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    相关资源
    最近更新 更多