索引器:列表索引超出i中的范围

2024-10-05 15:25:08 发布

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

我对Python非常陌生。我有一些R中的代码,我正试图用Python重写,我遇到了一个我似乎找不到答案的问题-抱歉,如果这个问题已经得到了答案,或者答案很明显,我已经搜索了,无法修复我的问题

我有一个“高度”列表,它是来自电子表格的481个数字的一列。我希望使用hrc,一个从最小高度值到最大高度值的列表,长度与高度列表相同,但所有值间隔相等。对于hrc中的每个值,我希望通过以下代码运行它,但我得到Indexerror:list index超出范围

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))

谢谢你的帮助


Tags: 答案代码列表间隔len高度数字电子表格
1条回答
网友
1楼 · 发布于 2024-10-05 15:25:08

不要索引到列表中(如果不需要的话)-迭代它的值

检查你的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)   

输出:

[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]

相关问题 更多 >