[英]Why am I getting this Python Index error?
使用代码时出现以下索引错误。 该代码用于Aroon指标,该指标用于股票的技术分析。 错误消息显示以下内容。 我正在使用Python27。
追溯(最近一次通话最近):aroon(20)中的文件“ C:\\ Python \\ Aroon.py”,第46行,aroon中的文件“ C:\\ Python \\ Aroon.py”,第37行print highp [x] IndexError:索引106超出了尺寸为106的轴0的范围
样本数据可位于http://sentdex.com/sampleData.txt上,我已将其复制到自己的文本文件中。 代码如下。 它会打印数据,但随后出现以下错误消息,并且我试图找出原因。
import numpy as np
import time
sampleData = open("sampleData.txt", "r").read()
splitData = sampleData.split("\n")
date, closep, highp, lowp, openp, volume = np.loadtxt(splitData,delimiter=",", unpack=True)
def aroon(tf):
AroonUp = []
AroonDown = []
AroonDate = []
x = tf
while x <= len(date):
Aroon_Up = ((highp[x-tf:x].tolist().index(max(highp[x-tf:x])))/float(tf))*100#numpy array to list.
Aroon_Down = ((lowp[x-tf:x].tolist().index(min(lowp[x-tf:x])))/float(tf))*100#numpy array to list.
AroonUp.append(Aroon_Up)
AroonDown.append(Aroon_Down)
AroonDate.append(date[x])
x+=1
print "######"
print highp[x] # THIS IS LINE 37
print Aroon_Up
print "=="
print lowp[x]
print Aroon_Down
print "#####"
return AroonDate,AroonUp,AroonDown
aroon(20)
您应该更改此行:
while x <= len(date):
对此:
while x < len(date):
您的文件中有106行,它正在寻找第107行(从零开始)。
请记住,在Python中,索引从0而不是1开始len(date) == 106
,因此最大的有效索引是10 5 ,而不是106。尝试将while
条件更改为
while x < len(date):
Python开发人员已经竭尽全力确保几乎不需要手动索引,正是因为它容易出错。
解决问题的更Python化方法是,您需要序列中的两个元素,日期(可能应该称为日期顺便说一句),而这些元素的索引是使用枚举:
for x, date in enumerate(dates):
if x < tf:
continue
# more code
或已建议使用范围:
for x in range(tf, len(dates)):
# more code
我个人将使用枚举。
附带说明一下,我建议使用描述性的变量名,这样其他人(和您自己)就可以更轻松地阅读代码。
问题在于如何在Python中指定范围: highp[x-tf:x]
。
此列表中的最后一个索引是x-1
,但是您正在尝试打印索引x
。
在列表中指定范围时,不包括最后一个元素。 请参阅Python shell中的以下示例:
>>> a=[0,1,2,3]
>>> print a[0:1]
[0]
>>> print a[0:4]
[0, 1, 2, 3]
>>> print a[3:4]
[3]
>>> print a[0:5]
[0, 1, 2, 3]
>>> print a[0:6]
[0, 1, 2, 3]
>>> print a[0]
0
>>> print a[3]
3
>>> print a[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
lowp[x-tf:x]
您将lowp[x-tf:x]
同样的问题
第二个问题是先增加x( x+=1
),然后在打印语句中将x用作索引,则应该颠倒顺序:
print "######"
print highp[x] # THIS IS LINE 37
print Aroon_Up
print "=="
print lowp[x]
print Aroon_Down
print "#####"
x+=1
您可以使用for循环。请参见python shell中的以下示例
对于xrange(1,4)中的x:...打印x ... 1 2 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.