首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >增加python中列表的大小

增加python中列表的大小
EN

Stack Overflow用户
提问于 2018-06-10 03:28:17
回答 1查看 2.8K关注 0票数 -1

下面的程序给出了错误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也不起作用

EN

回答 1

Stack Overflow用户

发布于 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 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50777787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档