索引错误:列表超出范围

时间:2010-05-27 03:12:25

标签: python

from string import Template
from string import Formatter
import pickle
f=open("C:/begpython/text2.txt",'r')
p='C:/begpython/text2.txt'
f1=open("C:/begpython/text3.txt",'w')
m=[]
i=0
k='a'
while k is not '':
    k=f.readline()
    mi=k.split('  ')
    m=m+[mi]
    i=i+1

print m[1]

f1.write(str(m[3]))
f1.write(str(m[4]))

x=[]
j=0
while j<i:
    k=j-1
    l=j+1
    if j==0 or j==i:
       j=j+1
    else:
        xj=[]
        xj=xj+[j]
        xj=xj+[m[j][2]]
        xj=xj+[m[k][2]]
        xj=xj+[m[l][2]]
        xj=xj+[p]
        x=x+[xj]
        j=j+1

f1.write(','.join(x))




f.close()
f1.close()

它表示第33行,xj = xj + m [l] [2] 有索引错误,列表超出范围

请帮忙  提前谢谢

2 个答案:

答案 0 :(得分:2)

假设我是10然后在while循环的最后一次运行时j是9,现在你有l = j + 1所以l将是10但是m中的10行被索引0..9所以m [l] [2]会给出索引错误。

另外,如果您只是一次性将元素添加到列表中,那么代码看起来会好很多,例如:

x = x + [j,m [j] [2],m [k] [2],m [l] [2],p]

太空是眼睛最好的朋友!

答案 1 :(得分:1)

IndexError异常(列表索引超出范围)意味着您尝试使用超出数组范围的索引访问数组。您可以使用如下简单示例来查看此操作:

>>> a = [1, 2, 3]
>>> a[2]
3
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: list index out of range

我无法完全遵循您的代码,但该错误意味着:

  • l超出了m
  • 的范围
  • 2超出了m[l]
  • 的范围
相关问题