python 找到满足条件的索引区间(python find the index interval that satisfies the condition)

 

之前写过一篇 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)]

大家掌握了以上代码的用法,就可以把改算法推广到求等于某个值的区间,或者绝对值等于某个值的区间~

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