Weighted averaging a list
You could use numpy.average
to calculate weighted average.
In [13]: import numpy as npIn [14]: rate = [14.424, 14.421, 14.417, 14.413, 14.41]In [15]: amount = [3058.0, 8826.0, 56705.0, 30657.0, 12984.0]In [17]: weighted_avg = np.average(rate, weights=amount)In [19]: weighted_avgOut[19]: 14.415602815646439
for g in range(len(rate)): rate[g] = rate[g] * amount[g] / sum(amount)rate = sum(rate)
is the same as:
sum(rate[g] * amount[g] / sum(amount) for g in range(len(rate)))
which is the same as:
sum(rate[g] * amount[g] for g in range(len(rate))) / sum(amount)
which is the same as:
sum(x * y for x, y in zip(rate, amount)) / sum(amount)
Result:
14.415602815646439