从头到尾循环

Ant*_*sov 5 python algorithm while-loop

一开始,我使用python 2天,有更多的问题。以下来自他们。

我有一个列表(3297 项),我想从 end where value != 'nan' 找到第一项的索引

示例:(索引,值)

[0]  378.966
[1]  378.967
[2]  378.966
[3]  378.967
....
....
[3295]  777.436
[3296]  nan
[3297]  nan
Run Code Online (Sandbox Code Playgroud)

如果想要找到带有索引的项目 - 3295

我的代码(从头到尾,一步一步)

    i = len(lasarr); #3297
    while (i >= 0):
            if not math.isnan(lasarr[i]):
                   method_end=i # i found !
                   break        # than exit from loop
            i=i-1 # next iteration
Run Code Online (Sandbox Code Playgroud)

运行并得到错误

Traceback (most recent call last):
  File "./demo.py", line 37, in <module>
    if not math.isnan(lasarr[i]):
IndexError: index out of bounds
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Tim*_*ker 2

您将开始超出列表中的最后一项。考虑

>>> l = ["a", "b", "c"]
>>> len(l)
3
>>> l[2]
'c'
Run Code Online (Sandbox Code Playgroud)

列表索引以 开始编号0,因此l[3]引发IndexError.

i = len(lasarr)-1
Run Code Online (Sandbox Code Playgroud)

解决这个问题。