for循环跳过第1和第2个元素

时间:2017-05-05 09:31:16

标签: python for-loop index-error

自周三以来,for循环在Python(2.7)中无法正常工作(使用Windows 10)。见屏幕截图。它跳过第1个和第二个元素(索引0和1)。类似的while循环工作正常。

Screen shot of simple example. For loop skips index 0 and 1. While loop wrks fine

1 个答案:

答案 0 :(得分:0)

你已经有了答案,但希望这可以解释发生了什么

>>> l =[1,2,3,4]
>>> l
[1, 2, 3, 4]
>>> for i in l:
...  print "value of i=",str(i), "value of l at index[i]", str(l[i])
... 
value of i= 1 value of l at index[i] 2
value of i= 2 value of l at index[i] 3
value of i= 3 value of l at index[i] 4
value of i= 4 value of l at index[i]
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range

l [4]没有可用值,因为起始位置是l [0]到l [3]