IndexError:列表索引超出范围Python inputMat

时间:2015-05-09 23:12:37

标签: python numpy

C:\Python34>python first.py q2data.txt
Traceback (most recent call last):
  File "first.py", line 13, in <module>
    inputMat.reshape(int(header[0]), int(header[1]))
IndexError: list index out of range

任何人都可以解释这个错误,我最近在Python中遇到了错误,我在其上阅读的大部分信息都对其进行了纠正,但没有解释发生了什么,该程序是:

import numpy as np
from sys import argv

script, filename = argv

txt = open(filename)

header = txt.readline().split()
inputArray = map(float, txt.readline().split())
txt.close()

inputMat = np.mat(inputArray)
inputMat.reshape(int(header[0]), int(header[1]))
inputMat.shape()

#takes q2data as input
def first(A):
    #Decomposes a nxn matrix A by PA=LU and returns L, U and P.
    n = len(A)
    L = [[0.0] * n for i in xrange(n)]
    U = [[0.0] * n for i in xrange(n)]

    #Creates the pivoting matrix for m.
    n = len(A)
    ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
    for j in xrange(n):
        row = max(xrange(j, n), key=lambda i: abs(A[i][j]))
        if j != row:
            ID[j], ID[row] = ID[row], ID[j]
    p = ID

    #perform matrix multplication
    TA = zip(*A)
    A2 = [[sum(eP*ea for eP,ea in zip(P,a)) for a in TA] for P in p]

    for j in xrange(n):
        L[j, j] = 1.0
        for i in xrange(j+1):
            s1 = sum(U[k, j] * L[i, k] for k in xrange(i))
            U[i, j] = A2[i, j] - s1
        for i in xrange(j, n):
            s2 = sum(U[k, j] * L[i, k] for k in xrange(j))
            L[i, j] = (A2[i, j] - s2) / U[j, j]
    return (L, U, p)

print (first(inputMat))

2 个答案:

答案 0 :(得分:1)

你将在这一行上抛出异常:

inputMat.reshape(int(header[0]), int(header[1]))

在使用列表之前,您需要确保列表header实际上是2的长度。正在发生的事情是,当您执行filename时,输入文本文件split()的第一行包含少于2个单词。

答案 1 :(得分:1)

错误只在错误消息中描述:

File "first.py", line 13, in <module>
    inputMat.reshape(int(header[0]), int(header[1]))
IndexError: list index out of range

在第13行中,您指的是索引超出列表索引范围的元素,例如:

myList = [1,2,3]
print myList[0]
print myList[1]
print myList[2]
print myList[3]# This will throw an IndexError exception like yours,

因此,您需要确保标题列表至少包含两个元素:

header = txt.readline().split()

肯定有filename文件中的行或可能第一行少于两个元素。