find the starting and ending indices of values greater than 0 in a list

烈酒焚心 提交于 2019-12-23 06:41:19

问题


I am trying to find the start and stop index of numbers > 0 in list

cross = [7,5,8,0,0,0,0,2,5,8,0,0,0,0,8,7,9,3,0,0,0,3,2,1,4,5,0,0,0,7,5] 

I am getting the indexes of values > 0 followed by index of value = 0.

Desired output:

(0 2),(7 9), (14 17)..

Actual output:

(2 3), (7 8)..

My code

cross = [7,5,8,0,0,0,0,2,5,8,0,0,0,0,8,7,9,3,0,0,0,3,2,1,4,5,0,0,0,7,5)   
for i in range(0,len(cross)): 
    if cross[i]==0:
        while(cross[i-1]>0):
            i+=1
            print(i-1,i)  

回答1:


How about using some flags to track where you are in the checking process and some variables to hold historical info?

This is not super elegant code but it is fairly simple to understand I think and fairly robust for the use case you gave.

My code

cross = [7,5,8,0,0,0,0,2,5,8,0,0,0,0,8,7,9,3,0,0,0,3,2,1,4,5,0,0,0,7,5] 
foundstart = False
foundend = False
startindex = 0
endindex = 0
for i in range(0, len(cross)):
    if cross[i] != 0:
        if not foundstart:
            foundstart = True
            startindex = i
    else:
        if foundstart:
            foundend = True
            endindex = i - 1

    if foundend:
        print(startindex, endindex)
        foundstart = False
        foundend = False
        startindex = 0
        endindex = 0

if foundstart:
    print(startindex, len(cross)-1)

Output

0 2
7 9
14 17
21 25
29 30


来源:https://stackoverflow.com/questions/48076780/find-the-starting-and-ending-indices-of-values-greater-than-0-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!