在简单的python for循环上列出索引超出范围错误 [英] List index out of range error on simple python for loop
本文介绍了在简单的python for循环上列出索引超出范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以向我解释为什么此for循环不起作用.我正在尝试在另一个程序中使用类似的东西来循环使用N作为参数的列表.
Can someone explain to me why this for loop doesn't work. I'm trying to use something like this in another program to loop through a list using this N as a parameter.
N = [20,40,60,80]
for j in N:
print(j)
for i in range(0,N[j]):
print(i)
提前谢谢!
推荐答案
您超出范围,因为j正在获取N数组元素的值,而不是索引.因此,j不是0、1、2、3,而是20、40、60、80.
因此,当您到达for i in range((0, N[j])
时,您要输入N [20],这远远超出了N列表的长度.
You're out of range, because j is taking the values of the elements of the N array, not the index. So, j is not 0, 1, 2, 3 but rather 20, 40, 60, 80.
So, when you get to for i in range((0, N[j])
, you're asking for N[20], which is well beyond the length of the N list.
您可以这样做:
N = [20,40,60,80]
for j in range(len(N)):
# ^^^^^^^^^^^^^
print(j)
for i in range(0,N[j]):
print(i)
这篇关于在简单的python for循环上列出索引超出范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文