简体   繁体   English

for循环跳过第一和第二元素

[英]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循环也可以正常工作。

简单示例的屏幕截图。 For循环跳过索引0和1。

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.

相关问题 循环遍历两个列表以查找第一个列表中的元素是否存在于第二个列表中 - loop through two lists to find if an element from 1st list exists in the 2nd list 无法获取列表的第一个和第二个元素 - Cannot get 1st and 2nd element of a list 嵌套在for循环中的Python在第一次循环的第二次迭代中未执行第二次循环 - Python nested for loop does not execute 2nd for loop on 2nd iteration of 1st loop 从列表列表中删除第一个元素,然后是第一个和第二个元素[保留] - Removing the 1st element then 1st and 2nd element from a list of lists [on hold] 在执行双重'for循环'时,如何将第一个for循环的结果放入第二个for循环Dataframe? - in performing double 'for loop', how to put results of 1st for loop into 2nd for loop Dataframe? Python:如果列表中的第一个元素重复并且第二个元素在列表系列中最低,则删除列表中的列表 - Python: delete list in list if 1st element in list is duplicated and 2nd element is lowest in lists series 比较2D列表的第一个元素并在第二个元素上进行操作 - Compare 1st element of a 2D list and operate on 2nd element 如何在python中的2D列表中比较第一个元素并操作第二个元素 - How to compare 1st element and operate 2nd element in 2D list in python TensorFlow:如何将张量的行与具有相同第一个元素的张量的第二个元素相加来合并? - TensorFlow: How to combine rows of tensor with summing the 2nd element of tensor which has the same 1st element? 如果出现异常,则跳出第二个 for 循环并继续执行第一个 for 循环中的内容 - If exception, break out of the 2nd for loop and continue with what's in the 1st for loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM