在python中增加列表的大小

2024-09-28 05:15:29 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的程序给出错误索引器错误:列表索引超出范围

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个值,它就可以工作了

^{pr2}$

所以,为什么它不能处理5600个值,这表明索引超出范围,但它使用1000个值?在

尝试使用列表的Len也不起作用


Tags: in程序列表forby错误rangetotal
1条回答
网友
1楼 · 发布于 2024-09-28 05:15:29

如果你有5600个元素的列表。将它们转换成字符串,而不增加其数量。您迭代5600次,在每次迭代中,您将k增加4倍,并使用k-结果:index error索引到列表中

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 

相关问题 更多 >

    热门问题