python 找到滿足條件的索引區間(python find the index interval that satisfies the condition)
阿新 • • 發佈:2021-07-02
之前寫過一篇python 列表尋找滿足某個條件的開始索引和結束索引(python find the starting and ending indices of values that satisfy a certain condition in a list)的文章,因在實際專案中,這個演算法的執行速度慢,於是我想使用 python 執行效果高的 numpy 來實現相同的功能,於是就研究了一會,出了一版本效果和上面連結相同的,但是速度快了許多的演算法,分享給大家。
1 def first_and_last_index_fast(li, lower_limit, upper_limit):
2 result = []
3 if type(li) != np.ndarray:
4 li = np.array(li)
5 # 找到滿足條件的索引
6 index1 = np.where(np.logical_and(li >= lower_limit, li<=upper_limit))[0]
7 if index1.__len__() != 0:
8 # 找到index1差值等於1的索引
9 index2 = np.where(np.diff(index1) != 1)[0]
10 if index2.__len__() != 0:
11 result.append((index1[0], index1[index2[0]]))
12 temp = [(index1[index2[i]+1], index1[index2[i+1]]) for i in range(index2.__len__()-1)]
13 result.extend(temp)
14 result.append((index1[index2[-1]+1], index1[-1]))
15 else :
16 result.append((index1[0], index1[-1]))
17 return result
結果如下:
In [54]: a = [-1, 0, 34, 23, 5, 2, 8, 2, 0, 1, 4, -4, 6]
In [55]: first_and_last_index_fast(a, 0, 3)
Out[55]: [(1, 1), (5, 5), (7, 9)]
大家掌握了以上程式碼的用法,就可以把改演算法推廣到求等於某個值的區間,或者絕對值等於某個值的區間~