简体   繁体   English

为什么会出现此Python索引错误?

[英]Why am I getting this Python Index error?

I am getting the following index error when I use my code. 使用代码时出现以下索引错误。 This code is for a Aroon indicator which is used for technical analysis for stocks. 该代码用于Aroon指标,该指标用于股票的技术分析。 The error message says the following. 错误消息显示以下内容。 I am using Python27. 我正在使用Python27。

Traceback (most recent call last): File "C:\\Python\\Aroon.py", line 46, in aroon(20) File "C:\\Python\\Aroon.py", line 37, in aroon print highp[x] IndexError: index 106 is out of bounds for axis 0 with size 106 追溯(最近一次通话最近):aroon(20)中的文件“ C:\\ Python \\ Aroon.py”,第46行,aroon中的文件“ C:\\ Python \\ Aroon.py”,第37行print highp [x] IndexError:索引106超出了尺寸为106的轴0的范围

The sample data can be located at http://sentdex.com/sampleData.txt I copied this to a text file of my own. 样本数据可位于http://sentdex.com/sampleData.txt上,我已将其复制到自己的文本文件中。 The code is below. 代码如下。 It prints the data but then I get the following error message and i'm trying to figure out why. 它会打印数据,但随后出现以下错误消息,并且我试图找出原因。

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)

You should change this line: 您应该更改此行:

while x <= len(date):

to this: 对此:

while x < len(date):

There are 106 lines in your file, and it's looking for the 107th line (zero based). 您的文件中有106行,它正在寻找第107行(从零开始)。

请记住,在Python中,索引从0而不是1开始len(date) == 106 ,因此最大的有效索引是10 5 ,而不是106。尝试将while条件更改为

while x < len(date):

The Python devs has gone to great lengths to make sure that you almost never have to manually index, precisely because it us error prone. Python开发人员已经竭尽全力确保几乎不需要手动索引,正是因为它容易出错。

The more Pythonic way to solve a problem where you want both the elements in a sequence, date, (which should probably be called dates btw) AND the index of these elements is to use enumerate: 解决问题的更Python化方法是,您需要序列中的两个元素,日期(可能应该称为日期顺便说一句),而这些元素的索引是使用枚举:

for x, date in enumerate(dates):
    if x < tf:
        continue
    # more code

or as has already been suggested, to use range: 或已建议使用范围:

for x in range(tf, len(dates)):
    # more code

Personally I would use the enumerate. 我个人将使用枚举。

On a side note, I recommend to use descriptive variable names, that makes it easier for others (and yourself) to read the code. 附带说明一下,我建议使用描述性的变量名,这样其他人(和您自己)就可以更轻松地阅读代码。

The problem lies with how ranges are specified in Python: highp[x-tf:x] . 问题在于如何在Python中指定范围: highp[x-tf:x]

The last index in this list is x-1 , but you are trying to print index x . 此列表中的最后一个索引是x-1 ,但是您正在尝试打印索引x

When specifying a range in a list, the last element is not included. 在列表中指定范围时,不包括最后一个元素。 See the following example in the Python shell: 请参阅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
>>> 

You will have the same problem with lowp[x-tf:x] lowp[x-tf:x]您将lowp[x-tf:x]同样的问题

The second issue is that you increment x first ( x+=1 ) and then use x as an index in you print statement, you should reverse the order: 第二个问题是先增加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

you could use the for loop.See the following example in the python shell 您可以使用for循环。请参见python shell中的以下示例

for x in xrange(1,4): ... print x ... 1 2 3 对于xrange(1,4)中的x:...打印x ... 1 2 3

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

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