简体   繁体   English

Python中的索引超出范围错误

[英]Index out of range error in Python

I keep getting an error saying 'list index out of range' for my change_array[i] += 0 and change_array[i] += roc. 我不断收到一条错误消息,说我的change_array [i] + = 0和change_array [i] + = roc的“列表索引超出范围”。 I've also tried just using a '=' and that doesn't work either. 我也尝试过仅使用'=',但这也不起作用。

   #define variables for a loop
   change_array = []
   roc = 0

   #iterate to find the change percentage
   for i in range (0, end_year_index+1):
       if i == 0:
          change_array[i] += 0
       else:
           roc = ((population[i] - population[i-1])/ (population[i-1]))
           change_array[i] += roc 

我假设您想向change_array添加元素,如果是,则需要使用change_array.append(your_element)

change_array = [] is an empty array, therefore there is no 0 element. change_array = []是一个空数组,因此没有0元素。 0 element is the first element in arrays. 0元素是数组中的第一个元素。

array = ["one", "two"]

array[0] is "one", array[1] is "two" array[0]为“一个”, array[1]为“两个”

@Ekinydre gave you a good solution, but I just wanted to elaborate on the error you got. @Ekinydre为您提供了一个很好的解决方案,但我只是想详细说明您遇到的错误。

When you have a list like change_array = [1, 2, 3] , then change_array[i] accessed element i (lists use 0-based indices in Python). 当您具有诸如change_array = [1, 2, 3]change_array[i]访问元素i (列表在Python中使用基于0的索引)。 Also, += in Python is not an append operator, but an increment operator. 另外,Python中的+=不是追加运算符,而是增量运算符。 So change_array[i] += 10 you are adding 10 to the list element at position i . 所以change_array[i] += 10就是在位置i处的list元素上加10

You could just append to change_array as @Ekinydre suggests, but given your code it may be safer (though less pythonic) to do something like the following: 您可以按照@Ekinydre的建议appendchange_array ,但是考虑到您的代码,执行以下操作可能更安全(虽然不如Pythonic):

#define variables for a loop
#create a list of 0 of length end_year_index
change_array = [0]*end_year_index
roc = 0

#iterate to find the change percentage
for i in range (0, end_year_index+1):
    if i == 0:
       change_array[i] += 0
    else:
        roc = ((population[i] - population[i-1])/ (population[i-1]))
        change_array[i] += roc

A slightly more pythonic way could look like this: 稍微更pythonic的方式可能是这样的:

change_array = [(population[i] - population[i-1]) / population[i-1] \
                    for i in range(1, end_year_index+1)]

Note: this last solution won't have the initial 0 at the beginning of change_array . 注意:这最后一个解决方案在change_array的开头不会以0开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM