在使用python列表的时候,咱们常常须要找到知足某个条件的数的开始索引和结束索引,即知足某个条件的数的区间范围,本文以寻找绝对值大于等于0且小于等于3的数值区间为例,代码以下所示:python
这是我在作项目写python代码的时候最常使用到的函数之一,分享给你们。app
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
运行结果以下:spa