简体   繁体   English

IndexError:列出索引超出范围,如果

[英]IndexError: list index out of range in if

i am extremely new to Python. 我是Python的新手。 I have some code in R that I am trying to rewrite in Python and I've come across an issue that I can't seem to find an answer to - apologies if this has already been answered or the answer is obvious, I have searched and can't fix my issue. 我在R中有一些代码正在尝试用Python重写,但遇到了一个我似乎找不到答案的问题-如果已经回答或答案很明显,我很抱歉,我已经搜索过并且无法解决我的问题。

I have a list 'height' which is a column of 481 numbers from a spreadsheet. 我有一个列表“高度”,它是电子表格中481个数字的列。 I wish to use hrc, a list from the min to the max values of height, of the same length as the height list, but all values equally spaced. 我希望使用hrc,它是从高度的最小值到最大值的列表,其长度与高度列表相同,但所有值均等距。 For each value in hrc i want to run it through the following code, but i get Indexerror: list index out of range. 对于hrc中的每个值,我想通过以下代码运行它,但出现Indexerror:列表索引超出范围。

hrc = np.linspace(min(height),max(height),len(height))
Qrc = []
for i in range(0,len(hrc)): 
  if(hrc[i]<0.685): 
      Qrc.append(30.69*((hrc[i]-0.156)**1.115))
  elif(0.685<=hrc[i] and hrc[i]<1.917):
      Qrc.append(27.884*((hrc[i]-0.028)**1.462))
  elif(1.917<=hrc[i]):
      Qrc.append(30.127*((hrc[i]-0.153)**1.502))

I appreciate any help! 感谢您的帮助!

Do not index into lists (if you do not have to) - iterate over its values. 不要索引到列表中(如果不需要的话)-遍历其值。

Check your if conditions, you can simplify them - if a lower range would have fit, the next range does not need to check if the value now is bigger as the lower range (if it was, you wouldnt be checking that one now): 检查您if条件,可以简化他们-如果一个较低的范围内将有合,在未来的范围并不需要检查,如果该值现在是更大的作为下范围(如果是,你不会是现在检查一个):

import numpy as np
height = [i/100.0 for i in range(0,200,20)]
hrc = np.linspace(min(height),max(height),len(height))

Qrc = []
for value in hrc: 
    if value < 0.685 : 
        Qrc.append(30.69*((value-0.156)**1.115))
    elif value < 1.917 :
        Qrc.append(27.884*((value-0.028)**1.462))
    else:
        Qrc.append(30.127*((value-0.153)**1.502))

print(len(height))  # 10
print(len(hrc))     # 10

print(hrc)   
print(Qrc)   

Output: 输出:

[0.  0.2 0.4 0.6 0.8 1.  1.2 1.4 1.6 1.8]
[nan, 0.942858721586344, 6.367024848753282, 12.411632276269644, 
 19.100800437337597, 26.749961012743743, 35.16634580199501, 
 44.275837504844475, 54.021755132798525, 64.35896171368269]

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

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