从结束到开始循环

问题描述 投票:0回答:4

一开始我使用python 2天,问题比较多。 下面是他们的一张。

我有一个列表(3297 个项目),我想从末尾找到第一个项目的索引,其中 value != '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

我做错了什么?

python algorithm while-loop
4个回答
2
投票

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

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

列表索引以

0
开头编号,因此
l[3]
会引发
IndexError

i = len(lasarr)-1

解决了这个问题。


2
投票

你的代码是否会引发

IndexError
? 它应该 ;-)
lasarr
有 3297 个项目,包括
lasarr[0]
lasarr[3296]
lasarr[3297]
not 是列表的一部分:那是超出列表末尾的位置。 像这样开始你的代码:

i = len(lasarr) - 1

然后

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


2
投票

您从错误的位置开始,数组的开始索引从

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

-1
投票

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

l = ['a', 'b', 'nan', 'c', 'nan']
lastindex = [x for x in enumerate (l) if x [1] != 'nan'] [-1] [0]
print (lastindex)
© www.soinside.com 2019 - 2024. All rights reserved.