Python-加权平均列表 [英] Python - Weighted averaging a list
问题描述
感谢您的回复.是的,我正在寻找加权平均值.
Thanks for your responses. Yes, I was looking for the weighted average.
rate = [14.424, 14.421, 14.417, 14.413, 14.41]
amount = [3058.0, 8826.0, 56705.0, 30657.0, 12984.0]
我想要基于底部列表中每个项目的顶部列表的加权平均值.
I want the weighted average of the top list based on each item of the bottom list.
因此,如果排名第一的下一项很小(例如3,058,而总数为112,230),那么排名第一的第一项对榜首平均值的影响应较小.
So, if the first bottom-list item is small (such as 3,058 compared to the total 112,230), then the first top-list item should have less of an effect on the top-list average.
这是我尝试过的一些方法.它给了我看似正确的答案,但是我不确定它是否符合我的要求.
Here is some of what I have tried. It gives me an answer that looks right, but I am not sure if it follows what I am looking for.
for g in range(len(rate)):
rate[g] = rate[g] * (amount[g] / sum(amount))
rate = sum(rate)
在将其他响应与我的代码进行比较之后,我决定使用邮政编码以使其尽可能短.
After comparing other responses with my code, I decided to use the zip code to keep it as short as possible.
推荐答案
for g in range(len(rate)):
rate[g] = rate[g] * amount[g] / sum(amount)
rate = sum(rate)
与以下相同:
sum(rate[g] * amount[g] / sum(amount) for g in range(len(rate)))
与以下相同:
sum(rate[g] * amount[g] for g in range(len(rate))) / sum(amount)
与以下相同:
sum(x * y为x,y为zip(比率,金额))/sum(金额)
sum(x * y for x, y in zip(rate, amount)) / sum(amount)
结果:
14.415602815646439
这篇关于Python-加权平均列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!