【问题标题】:for loop skipping 1st and 2nd elementfor循环跳过第一个和第二个元素
【发布时间】:2017-05-05 09:31:16
【问题描述】:

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

【问题讨论】:

  • i 是元素而不是索引......并且将代码和错误作为文本而不是图像发布。
  • 星期三发生了什么事?
  • 当你做 for i in list 时 i 成为列表的一个元素而不是索引,所以你不能做 list[i]
  • @tiwo 脑雾?

标签: python for-loop index-error


【解决方案1】:

好的,所以如果你使用for 循环,你应该去:

for i in my_list:
    print i

或者:

for i, element in enumerate(my_list):
    print my_list[i]

在这两种情况下都不要调用您的变量list,因为它是实际列表的保留关键字。

【讨论】:

    【解决方案2】:

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

    >>> 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]

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 2014-08-28
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      相关资源
      最近更新 更多