python 列表寻找满足某个条件的开始索引和结束索引(python find the starting and ending indices of values that satisfy a certain condition in a list)

在使用python列表的时候,我们经常需要找到满足某个条件的数的开始索引和结束索引,即满足某个条件的数的区间范围,本文以寻找绝对值大于等于0且小于等于3的数值区间为例,代码如下所示:

这是我在做项目写python代码的时候最常使用到的函数之一,分享给大家。

参考资料: https://stackoverflow.com/questions/48076780/find-starting-and-ending-indices-of-list-chunks-satisfying-given-condition

 1 # 列表中找到符合要求的数的起始索引和结尾索引
 2 def first_and_last_index(li, lower_limit=0, upper_limit=3):
 3     result = []
 4     foundstart = False
 5     foundend = False
 6     startindex = 0
 7     endindex = 0
 8     for i in range(0, len(li)):
 9         if abs(li[i]) >= lower_limit and abs(li[i]) <= upper_limit:
10             if not foundstart:
11                 foundstart = True
12                 startindex = i
13         else:
14             if foundstart:
15                 foundend = True
16                 endindex = i - 1
17 
18         if foundend:
19             result.append((startindex, endindex))
20             foundstart = False
21             foundend = False
22             startindex = 0
23             endindex = 0
24 
25     if foundstart:
26         result.append((startindex, len(li)-1))
27     return result

运行结果如下:

 

注意:这里我用的是判断数据的绝对值是否在某个区间,你也可以去掉绝对值,或者改成求等于某个值的区间,这些在你熟悉了代码之后都可以自行调整。

原文地址:https://www.cnblogs.com/ttweixiao-IT-program/p/13331231.html