以下程序给出错误IndexError:list index超出范围
newlist=[2,3,1,5,6,123,436,124,223.......,213,213,213,56,2387567,3241,2136]
# total 5600 values seprated by commas in the above list
emptylist = []
for values in newlist:
convstr = str(values)
convstr = convstr.split(",")
emptylist.extend(convstr)
k=0
for i in range(5600):
for j in range(0,4):
print(i,j,emptylist[k])
k=k+1
但是当我使用相同的程序时,newlist包含1000个值,它可以正常工作
newlist=[2,3,1,5,6,123,436,124,223.......,213]
# total 1000 values seprated by commas in the above list
emptylist = []
for values in newlist:
convstr = str(values)
convstr = convstr.split(",")
emptylist.extend(convstr)
k=0
for i in range(1000):
for j in range(0,4):
print(i,j,emptylist[k])
k=k+1
那么为什么它没有使用5600值显示索引超出范围但是它使用了1000个值?
TRIED使用列表中的Len也不起作用
答案 0 :(得分:1)
如果您有5600个元素的列表。您将它们转换为不增加其数量的字符串。迭代5600次,在每次迭代中,您将k
增加4倍,然后使用k
索引到列表中 - 结果:索引错误
newlist=[2,3,1,5,6,123,436,124,223.......,213,213,213,56,2387567,3241,2136]
# total 5600 values seprated by commas in the above list
emptylist = []
for values in newlist:
convstr = str(values) # values is ONE number, its string is also one number
convstr = convstr.split(",") # there are no , in numbers but you get a [number]
emptylist.extend(convstr) # this adds the string of a int to the list
k=0 # you index by k
for i in range(5600): # you do this 5600 times
for j in range(0,4): # your print AND INCREASE k 4 times
print(i,j,emptylist[k])
k=k+1 # after about 5600 / 4 iterations of the loop your k is
# larger then the amount in your list