简体   繁体   中英

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 ie:

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 of m , or
  • 2 exceeds the bounds of m[l]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM