Return index of the last nonzero element in the list

I get the data in the following format:

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

each line representing a different input. Lists can be longer than 7 items. I need to return the index position of the last nonzero element, so:

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

This code does this most of the time:

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

However, it does not work when there are two identical numbers, as in the first example above, which returns 0because it -2is in both the 0th and the first positions of the list.

So, how to get the index of the last non-zero list item, even if there are items with the same value?

+4
source share
8 answers

reversed , ,

>>> def get_last_non_zero_index(d, default=None):
...     rev = (len(d) - idx for idx, item in enumerate(reversed(d), 1) if item)
...     return next(rev, default)
...
>>> print(get_last_non_zero_index([-2, -2, 0, 0, 0, 0, 0]))
1
>>> print(get_last_non_zero_index([-2, 20, -1, 0, 3, 0, 0]))
4
>>> print(get_last_non_zero_index([0, 0, 0]))
None
>>> print(get_last_non_zero_index([]))
None

default , .

+4

, , for :

last_nonzero_index = None
for idx, item in enumerate(originalList):
    if item != 0:
        last_nonzero_index = idx
+3

, : .

a = [-2, -2, 0, 0, 0, 0, 0]
b = [-2, 20, -1, 0, 3, 0, 0]

def index_of_last_nonzero(lst):
    for i, value in enumerate(reversed(lst)):
        if value != 0:
            return len(lst)-i-1
    return -1

print(index_of_last_nonzero(lst=a))  # -> 1
print(index_of_last_nonzero(lst=b))  # -> 4

, reversed ( enumerate). -1.

+2

:

def getLastNonZeroIndex(originalList):

    # Create a new list from the old list
    # so changes don't change the old list
    newList = list(originalList)

    # Keep checking to see if last item equals 0
    # If it does, remove it from newList
    while newList[-1] == 0:
        newList.pop()

    # Once the item at newList[-1] != 0
    # Return index of the last element
    return len(newList)-1

, , , , , .

+1

Here is a pythonic and optimized approach using itertools.takewhile():

from itertools import takewhile
from operator import not_
len(lst) - sum(1 for _ in takewhile(not_, reversed(lst))) - 1

Demo:

In [115]: lst = [-2, -2, 0, 0, 0, 0, 0]
In [118]: len(lst) - sum(1 for _ in takewhile(lambda x : not bool(x), lst[::-1])) - 1
Out[118]: 1

In [119]: lst = [-2, 20, -1, 0, 3, 0, 0]

In [120]: len(lst) - sum(1 for _ in takewhile(lambda x : not bool(x), lst[::-1])) - 1
Out[120]: 4

Here is a scam with other answers on a longer list:

In [141]: lst = lst * 1000

In [142]: %timeit len(lst) - len(list(takewhile(not_, reversed(lst)))) - 1
1000000 loops, best of 3: 758 ns per loop

In [143]: %timeit get_last_non_zero_index(lst)
1000000 loops, best of 3: 949 ns per loop

In [146]: %timeit index_of_last_nonzero(lst)
1000000 loops, best of 3: 590 ns per loop
+1
source

Understanding the list does the trick:

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

output:

[0, 1, 2, 4]
+1
source
n_l = []
for i,v in enumerate(l): #enumerate returns the index - i, and value-v
    if v != 0:
        n_l.append(i) #keep the index if the value is not 0

n_l = sorted(n_l) #we then sort the list of indecies from least to greatest. the greatest index will be the last
greatest_non_zero_index = n_l[-1] #grab the last index

Here is another way to do it in one line!

greatest_non_zero_index = sorted([i for i,v in enumerate(l) if v != 0])[-1]
+1
source

The following should work:

def last_non_zero_index(my_list):
    temp = my_list[:]
    while temp[-1] == 0:
        del temp[-1]
    return len(temp) - 1

Conclusion:

>>> my_list = [-2, -2, 0, 0, 0, 0, 0]
>>> last_non_zero_index(my_list)
1
>>> my_list = [-2, 20, -1, 0, 3, 0, 0]
>>> last_non_zero_index(my_list)
4
+1
source

Source: https://habr.com/ru/post/1665003/


All Articles