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

这是一个通用的矢量化解决方案,使用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.average

l = 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],list_amounts[1],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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值