计算增长

2024-05-15 15:01:36 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我想从一个列表中计算出增长率的百分比

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)“索引器错误,索引超出范围”


Tags: in列表newforratedef错误pop
3条回答

NPE的建议将起作用,我还建议在需要列表的索引和值时使用枚举:

for pop_index,pop_val in enumerate(population):

在代码中,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(浮点数),就会得到一个浮点结果,随后的除法不会截断为整数。

对不起,我不能控制自己:

import numpy as np

growth_rate = np.exp(np.diff(np.log(population))) - 1

相关问题 更多 >