下面的程序给出了错误IndexError: list index out range
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
但当我现在使用包含1000个值的newlist的相同程序时,它可以工作
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个值呢?
尝试使用Len of the list也不起作用
发布于 2018-06-10 03:45:46
如果你有一个包含5600个元素的列表。您可以将它们转换为不会增加其数量的字符串。您迭代了5600次,在每次迭代中,使用k
- k
:index error将结果增加4倍,并对列表进行索引
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
https://stackoverflow.com/questions/50777787
复制相似问题