Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index where values in a list, increase value?

I have a list that looks like:

mot = [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0]

I need to append to a list, the index when the element changes from 0 to 1 (and not from 1 to 0).

I've tried to do the following, but it also registers when it changes from 1 to 0.

i = 0 
while i != len(mot)-1:
    if mot[i] != mot[i+1]:
        mot_daily_index.append(i)
    i += 1

Also, but not as important, is there a cleaner implementation?

like image 946
hcp Avatar asked Jun 09 '20 12:06

hcp


People also ask

How do you find an index of a value in a list?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.

Which returns the index position of a value in a list of values?

The index() method returns the index of the given element in the list.

How do you find the index of a specific value in Python?

To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.


2 Answers

Here is how you can do that with a list comprehension:

mot = [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0]
mot_daily_index = [i for i,m in enumerate(mot) if i and m and not mot[i-1]]
print(mot_daily_index)

Output:

[7, 24]

Explanation:

  • list(enumerate([7,5,9,3])) will return [(0, 7), (1, 5), (2, 9), (3, 3)], so the i in i for i, m in enumerate, is the index of m during that iteration.
like image 87
Ann Zen Avatar answered Oct 26 '22 19:10

Ann Zen


Use a list comprehension with a filter to get your indexes:

mot = [0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,0,0,0]

idx = [i for i,v in enumerate(mot) if i and v > mot[i-1]]
print(idx)

Output:

[7, 24]
like image 40
Patrick Artner Avatar answered Oct 26 '22 17:10

Patrick Artner