0

我在 python 中的数组索引有问题。在函数 readfile 它崩溃并打印:“列表索引超出范围”

inputarr        = []

def readfile(filename):
    lines = readlines(filename)
    with open(filename, 'r') as f:
        i = 0
        j= 0
        k = 0
        for line in f:
            line = line.rstrip("\n")
            if not line == '':
                inputarr[j][k] = line
                k += 1
                #print("\tnew entry\tj=%d\tk=%d" % (j, k))
            elif line == '':
                k = 0
                j += 1
                #print("new block!\tj=%d\tk=%d" % (j, k))
            i += 1
            processing(i, lines)   
4

2 回答 2

0

它发生是因为inputarr是空的。例如:

lst = []
lst[0] = 1 // error

在你的情况下:

inputarr = []
j = 0
...
inputarr[j][k] = line   // inputarr= []; j = 0; so inputarr[0] = ...!ERROR
于 2013-10-17T13:17:35.443 回答
0

此错误是由于您尝试分配的索引inputarr超出了列表的范围。这会导致 python 中的错误(与其他一些语言(如 javascript)不同,如果您尝试访问数组初始边界之外的索引,则会自动扩展数组)。

您需要预先填充inputarr以使其具有正确的形状和大小,或者您需要随时动态创建它。我更喜欢后者:

inputarr = [[]]
#           ^^  Set up the first row
def readfile(filename):
    lines = readlines(filename)
    with open(filename, 'r') as f:
        i = 0
        j= 0
        k = 0
        for line in f:
            line = line.rstrip("\n")
            if not line == '':
                inputarr[j].append(line)
#                          ^^^^^^^^       Add a new value to the end of the current row of inputarr
                k += 1
                #print("\tnew entry\tj=%d\tk=%d" % (j, k))
            elif line == '':
                k = 0
                inputarr.append([])
#               ^^^^^^^^^^^^^^^^^^^  Add a new blank row to inputarr
                j += 1
                #print("new block!\tj=%d\tk=%d" % (j, k))
            i += 1
            processing(i, lines)   
于 2013-10-17T14:02:14.390 回答