在使用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