循环从头到尾

时间:2013-10-04 05:28:56

标签: python algorithm while-loop

首先,我使用python 2天并且有更多问题。 从他们下面一个。

我有一个清单(3297项),我希望从结束找到第一项的索引值!='nan'

示例:(索引,值)

[0]  378.966
[1]  378.967
[2]  378.966
[3]  378.967
....
....
[3295]  777.436
[3296]  nan
[3297]  nan

如果想找到带索引的项目 - 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

运行并获取错误

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

我做错了什么?

4 个答案:

答案 0 :(得分:2)

你开始超越列表中的最后一项。考虑

>>> l = ["a", "b", "c"]
>>> len(l)
3
>>> l[2]
'c'

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

i = len(lasarr)-1

解决了这个问题。

答案 1 :(得分:2)

您的代码是IndexError吗?它应该;-) lasarr有3297项,lasarr[0]lasarr[3296]包含。 lasarr[3297] 是列表的一部分:这是位于列表末尾之外的位置。这样开始你的代码:

   i = len(lasarr) - 1

然后i将索引列表的最后一个元素。

答案 2 :(得分:0)

你从错误的位置开始,数组从0开始索引,所以i = len(lasarr) -1的位置不正确。

lasarr = [378.966, 378.967, 378.968, 378.969, nan]

for i in range(len(lasarr) - 1, -1,-1):
    if not math.isnan(lasarr[i]):
        break

答案 3 :(得分:-1)

由于您的列表很短,只需过滤它并取最后一项(及其索引):

l = ['a', 'b', 'nan', 'c', 'nan']
lastindex = [x for x in enumerate (l) if x [1] != 'nan'] [-1] [0]
print (lastindex)
相关问题