index error:list out of range
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()
It say line 33,xj=xj+m[l][2] has index error,list out of range
please help thanks in advance
Suppose i is 10 then on the last run of the while loop j is 9, now you have l = j + 1 so l will be 10 but your 10 lines in m are indexed 0..9 so m[l][2] will give an index error.
Also, you code would look a lot better if you just added the elements to your list in one go i.e:
x = x + [j, m[j][2], m[k][2], m[l][2], p]
Spaces are an eyes best friend!
The IndexError
exception (list index out of range) means that you have attempted to access an array using an index that is beyond the bounds of the array. You can see this in action using a simple example like this:
>>> 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
I can't exactly follow your code, but what that error means is that either:
l
exceeds the bounds ofm
, or2
exceeds the bounds ofm[l]
精彩评论