IndexError:列表索引超出范围'

时间:2012-02-17 23:36:49

标签: python loops indexing

我正在使用python编写代码以在ArcMAP中生成点shapefile。我有1000个随机可能的50分(在FileA(1000:50)中,我需要尝试所有这些。

每个点的坐标X = FileB(:,1)。每个点的坐标Y = FileB(:,2)。

生成一个序列,我占用了FileA的第一行,FileA(1,1)中的数字对应于FileB中第1点的新序列中的位置

我正在尝试创建一个循环,在其中我按照FileA每行中的位置创建这些序列。

我有一篇上一篇文章: AttributeError: 'str' object has no attribute 'toInteger'

我将'entry.toInteger()[0]'更改为'int(entry [])'。混合语言......

我有这个新错误:

'tempXYFile.writerow('{0},{1}'.format(coordinates[int(entry)][0],coordinates[int(‌​entry)][1])) IndexError: list index out of range' 

我会感激任何帮助!

这是我的代码:

import csv

# create 1000 XY sequences
print 'Start of the script'
sequences = csv.reader(open('50VolcanoPaleoOrder-11-01-2012.csv','rb'),delimiter=',')
coordinates = []

# read coordinates of volcanos and store in memory
print 'Start reading in the coordinates into the memory'
coordinates_file = csv.reader(open('seq50.csv','rb'),delimiter=',')   

for coordinate in coordinates[1:]:
    coordinates.append(coordinate)
del coordinates_file

i = 1
for sequence in sequences:
    print 'sequence # {0}'.format(i) 
    j = 1           
    tempXYFile = csv.writer(open('tempXY.csv','w+'),delimiter=',') #add the parameter to create a file if does not exist                  
    for entry in sequence:         
        tempXYFile.writerow('{0},{1}'.format(coordinates[int(entry)][0],coordinates[int(entry)][1]))
        print 'Entry # {0}: {1},{2}'.format(j, coordinates[int(entry)][0],coordinates[int(entry)][1]) 
        j = j + 1
    i = i + 1
    del tempXYFile

print 'End of Script'

1 个答案:

答案 0 :(得分:2)

Python中的错误消息不像某些语言中的编译错误那样难以理解;你应该试着去了解他们告诉你的事情。

IndexError: list index out of range

表示您正在使用不存在的索引访问列表。像“a = [1,2];打印[79]”之类的东西会给你这个消息。在这种情况下,如果问题在行

tempXYFile.writerow('{0},{1}'.format(coordinates[int(entry)][0],coordinates[int(‌​entry)][1]))

那么两个坐标都没有int(entry)-th元素,或者坐标[int(entry)]没有第0个或第1个元素的几率非常好。

所以在该行之前,尝试插入print语句:

print int(entry)
print coordinates
print coordinates[int(entry)]

看看你认为的不是什么。