[英]for loop skipping 1st and 2nd element
Since Wednesday, for loop is not working correctly in Python(2.7) in (with windows 10). 从周三开始,for循环在(带有Windows 10的)Python(2.7)中无法正常工作。 See screen shot.
参见屏幕截图。 Its skipping the 1st and somestimes the 2nd element (index 0 and 1).
它跳过第一个元素,有时跳过第二个元素(索引0和1)。 A similar while loop works fine.
类似的while循环也可以正常工作。
Okay, so if you are using for
loop you should either go: 好的,因此,如果您使用
for
循环,则应该执行以下任一操作:
for i in my_list:
print i
Or: 要么:
for i, element in enumerate(my_list):
print my_list[i]
In both cases don't call your variable list
as it is a reserved keyword for actual list. 在这两种情况下都不要调用变量
list
因为它是实际列表的保留关键字。
You already have an answer but hopefully this might explain what is going on 您已经有了答案,但希望这可以解释发生了什么
>>> 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
There is no value available at l[4] as the starting position is l[0] through to l[3] l [4]处没有可用的值,因为起始位置是l [0]至l [3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.