嗨,我想从列表中计算百分比的增长率
def growth():
population = [1, 3, 4, 7, 8, 12]
# new list for growth rates
growth_rate = []
# for population in list
for pop in population:
gnumbers = ((population[pop] - population[pop-1]) / population[pop-1] * 100)
growth_rate.append(gnumbers)
print growth_rate
growth()
但它在这里给我一个索引错误(gnumbers)" IndexError,index超出范围"
答案 0 :(得分:2)
在您的代码中pop
迭代population
的值,而不是索引。要遍历索引(零除外),请写:
for pop in range(1, len(population)):
另一件需要注意的事情是以下使用整数除法:
gnumbers = ((population[pop] - population[pop-1]) / population[pop-1] * 100)
^ HERE
这样做会将结果截断为整数。鉴于您的数据,您似乎很清楚,您不希望这样。以下是重写表达式以避免此问题的一种方法:
gnumbers = ((population[pop] - population[pop-1]) * 100.0 / population[pop-1])
一旦乘以100.0
(这是一个浮点数),就会得到浮点结果,后续除法不会截断为整数。
答案 1 :(得分:2)
import numpy as np
growth_rate = np.exp(np.diff(np.log(population))) - 1
答案 2 :(得分:0)
NPE建议使用什么,当你想要列表的索引和值时,我还建议使用枚举:
for pop_index,pop_val in enumerate(population):