dun.py
dun.py

Reputation: 73

Find the indices of first positive elements in list - python

I am trying to find the indices of the starting position of each positive value sequence. I only got the position of the positive values ​​in the code. My code looks like following:

index = []
for i, x in enumerate(lst):
  if x > 0:
    index.append(i)
print index

I expect the output of [-1.1, 2.0, 3.0, 4.0, 5.0, -2.0, -3.0, -4.0, 5.5, 6.6, 7.7, 8.8, 9.9] to be [1, 8]

Upvotes: 1

Views: 8977

Answers (2)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Currently you are selecting all indexes where the number is positive, instead you would want to collect the index only when a number switches from negative to positive.

Additionally you can handle all negative numbers, or numbers starting from positive as well

def get_pos_indexes(lst):

    index = []

    #Iterate over the list using indexes
    for i in range(len(lst)-1):

        #If first element was positive, add 0 as index
        if i == 0:
            if lst[i] > 0:
                index.append(0)
        #If successive values are negative and positive, i.e indexes switch over, collect the positive index
        if lst[i] < 0 and lst[i+1] > 0:
            index.append(i+1)

    #If index list was empty, all negative characters were encountered, hence add -1 to index
    if len(index) == 0:
        index = [-1]

    return index

print(get_pos_indexes([-1.1, 2.0, 3.0, 4.0, 5.0, -2.0, -3.0, -4.0, 5.5, 6.6, 7.7, 8.8, 9.9]))
print(get_pos_indexes([2.0, 3.0, 4.0, 5.0, -2.0, -3.0, -4.0, 5.5, 6.6, 7.7, 8.8, 9.9]))
print(get_pos_indexes([2.0,1.0,4.0,5.0]))
print(get_pos_indexes([-2.0,-1.0,-4.0,-5.0]))

The output will be

[1, 8]
[0, 7]
[0]
[-1]

Upvotes: 1

Derick
Derick

Reputation: 169

I think it would better if you use list comprehension

index = [i for i, x in enumerate(lst) if x > 0]

Upvotes: 2

Related Questions