在列表中查找值大于0的起始和结束索引

问题描述 投票:-4回答:1

我试图在列表中找到数字> 0的开始和停止索引

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] 

我得到值> 0的索引,然后索引值= 0。

期望的输出:

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

实际产量:

(2 3), (7 8)..

我的代码

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)  
python arrays list if-statement conditional
1个回答
1
投票

如何使用一些标志来跟踪您在检查过程中的位置以及一些用于保存历史信息的变量?

这不是超级优雅的代码,但我认为它相当简单,并且对于您提供的用例相当健壮。

我的代码

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)

产量

0 2
7 9
14 17
21 25
29 30
© www.soinside.com 2019 - 2024. All rights reserved.