如何获得一个列表的加权平均值,它的权重受Python 3.6中的变量的限制

如何获得一个列表的加权平均值,它的权重受Python 3.6中的变量的限制,第1张

概述我希望这个标题有意义.我想要达到的目的是获得不同价格的鞋子的加权平均价格.所以我举个例子: list_prices = [12,12.7,13.5,14.3]list_amounts = [85,100,30,54]BuyAmount = x 我想知道我的加权平均价格,以及我为每双鞋支付的最高价格如果我购买x量的鞋子(假设我想先买最便宜的) 这就是我现在拥有的(我使用numpy): if li 我希望这个标题有意义.我想要达到的目的是获得不同价格的鞋子的加权平均价格.所以我举个例子:

List_prices = [12,12.7,13.5,14.3]List_amounts = [85,100,30,54]BuyAmount = x

我想知道我的加权平均价格,以及我为每双鞋支付的最高价格如果我购买x量的鞋子(假设我想先买最便宜的)

这就是我现在拥有的(我使用numpy):

if List_amounts[0] >= BuyAmount:        avgprice = List_prices[0]        highprice = List_prices[0]    elif (sum(List_amounts[0: 2])) >= BuyAmount:        avgprice = np.average(List_prices[0: 2],weights=[List_amounts[0],BuyAmount - List_amounts[0]])        highprice = List_prices[1]    elif (sum(List_amounts[0: 3])) >= BuyAmount:        avgprice = np.average(List_prices[0: 3],List_amounts[1],BuyAmount - (sum(List_amounts[0: 2]))])        highprice = List_prices[2]    elif (sum(List_amounts[0: 4])) >= BuyAmount:        avgprice = np.average(List_prices[0: 4],List_amounts[2],BuyAmount - (sum(List_amounts[0: 3]))])        highprice = List_prices[3]    print(avgprice)    print(highprice)

此代码有效,但可能过于复杂和广泛.特别是因为我想能够处理20个项目的金额和价格表.

有什么更好的方法呢?

解决方法 这是一个通用的矢量化解决方案,使用cumsum替换那些切片的摘要和argmax,以获得用于设置IF-case *** 作的切片限制的适当索引 –

# Use cumsum to replace sliced summations - Basically all those # `List_amounts[0]`,`sum(List_amounts[0: 2]))`,`sum(List_amounts[0: 3])`,etc.c = np.cumsum(List_amounts)# Use argmax to decIDe the slicing limits for the intended slicing operations.# So,this would replace the last number in the slices - # List_prices[0: 2],List_prices[0: 3],etc.IDx = (c >= BuyAmount).argmax()# Use the slicing limit to get the slice off List_prices needed as the first# input to numpy.averagel = List_prices[:IDx+1]# This step gets us the weights. Now,in the weights we have two parts. E.g.# for the third-IF we have : # [List_amounts[0],BuyAmount - (sum(List_amounts[0: 2]))]# Here,we would slice off List_amounts limited by `IDx`.# The second part is sliced summation limited by `IDx` again.w = np.r_[List_amounts[:IDx],BuyAmount - c[IDx-1]]# Finally,plug-in the two inputs to np.average and get avgprice output.avgprice = np.average(l,weights=w)# Get IDx element off List_prices as the highprice output.highprice = List_prices[IDx]

我们可以进一步优化以删除连接步骤(使用np.r_)并获得avgprice,就像这样 –

slice1_sum = np.multiply(List_prices[:IDx],List_amounts[:IDx]).sum()        # or np.dot(List_prices[:IDx],List_amounts[:IDx])slice2_sum = List_prices[IDx]*(BuyAmount - c[IDx-1])weight_sum = np.sum(List_amounts[:IDx]) + BuyAmount - c[IDx-1]avgprice = (slice1_sum+slice2_sum)/weight_sum
总结

以上是内存溢出为你收集整理的如何获得一个列表的加权平均值,它的权重受Python 3.6中的变量的限制全部内容,希望文章能够帮你解决如何获得一个列表的加权平均值,它的权重受Python 3.6中的变量的限制所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1194094.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存