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