在列表中查找值大于0的起始和结束索引 [英] find the starting and ending indices of values greater than 0 in a list

查看:226
本文介绍了在列表中查找值大于0的起始和结束索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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] 

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

I am getting the indexes of values > 0 followed by index of value = 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)  


推荐答案

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

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.

我的代码

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

这篇关于在列表中查找值大于0的起始和结束索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆