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

``````list_prices = [12,12.7,13.5,14.3]
list_amounts = [85,100,30,54]
``````

``````    if list_amounts[0] >= BuyAmount:
avgprice = list_prices[0]
highprice = list_prices[0]

avgprice = np.average(list_prices[0: 2], weights=[list_amounts[0],BuyAmount - list_amounts[0]])
highprice = list_prices[1]

avgprice = np.average(list_prices[0: 3], weights=[list_amounts[0],list_amounts[1],BuyAmount - (sum(list_amounts[0: 2]))])
highprice = list_prices[2]

avgprice = np.average(list_prices[0: 4], weights=[list_amounts[0],list_amounts[1],list_amounts[2],BuyAmount - (sum(list_amounts[0: 3]))])
highprice = list_prices[3]

print(avgprice)
print(highprice)
``````

``````# 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.

# 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 :
# 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]
``````

``````slice1_sum = np.multiply(list_prices[:idx], list_amounts[:idx]).sum()
# or np.dot(list_prices[:idx], list_amounts[:idx])