返回列表中最后一个非零元素的索引 [英] return index of last non-zero element in list

查看:45
本文介绍了返回列表中最后一个非零元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以以下格式获取数据:

I get data in the following format:

[-2, -2, 0, 0, 0, 0, 0]
[-2, 20, -1, 0, 3, 0, 0]

,每行都是不同的输入.列表可以长于 7 个元素.我需要返回最后一个非零元素的索引位置,所以:

with each line being a different input. The lists could be longer than 7 elements. I need to return the index position of the last non-zero element, so:

[-2, -2, 0, 0, 0, 0, 0]
>>> 1
[-2, 20, -1, 0, 3, 0, 0]
>>> 4

以下代码大部分时间都在执行此操作:

The following code does this most of the time:

def getIndex(list):
    for element in reversed(list):
        if element != 0:
            return list.index(element)

但是,当有两个相同的数字时,这是不起作用的,如上面的第一个示例一样,该数字返回 0 ,因为 -2 在两个列表的第0位和第1位.

However, it doesn't work when there are two of the same numbers, as in the first example above, which returns 0 because -2 is in both the 0th and 1st position of the list.

那么,即使存在具有相同值的元素,如何获取列表中最后一个非零元素的索引?

So how to get the index of the last non-zero element of a list, even when there are elements with the same value?

推荐答案

列表理解可以解决问题:

List comprehension does the trick:

a = [-2, 20, -1, 0, 3, 0, 0]
ls = [i for i, e in enumerate(a) if e != 0]
print(ls)

输出:

[0, 1, 2, 4]

这篇关于返回列表中最后一个非零元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆