5

一开始我用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

我做错了什么?

4

4 回答 4

2

您从列表中的最后一项开始。考虑

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

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

i = len(lasarr)-1

解决这个问题。

于 2013-10-04T05:32:30.673 回答
2

你的代码在提高IndexError吗?它应该 ;-) 包含 lasarr3297 个项目lasarr[0]。不是列表一部分:这是列表末尾之外的位置。像这样开始你的代码:lasarr[3296]lasarr[3297]

   i = len(lasarr) - 1

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

于 2013-10-04T05:32:58.753 回答
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
于 2013-10-04T06:00:33.933 回答
-1

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

l = ['a', 'b', 'nan', 'c', 'nan']
lastindex = [x for x in enumerate (l) if x [1] != 'nan'] [-1] [0]
print (lastindex)
于 2013-10-04T05:33:08.197 回答