根据@ gnibbler的这个好答案,您可以自己重写代码以满足您的需要bisect
我稍微修改了@ gnibbler的代码,以便可以在您的情况下使用
一个优化是,由于你的阈值也是排序的,我们不需要每次都搜索整个列表,而是从最后一个结果索引开始
def reverse_binary_search(a, x, lo=0, hi=None):
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)/2
if x > a[mid][4]:
hi = mid
else:
lo = mid+1
return lo
my_list = [[3,0.99,1], [2,0.98,54], [10,.85,4], [1,0.7,10], [12,0.69,31], [12,0.65,43], [1.56,0]]
threshold = [0.97, 0.90, 0.83, 0.6]
index_list = []
last_index = 0
for t in threshold:
last_index = reverse_binary_search(my_list, t, last_index) # next time start search from last_index
index_list.append(last_index)
感谢@PhilCooper的宝贵建议。这是他提出的使用生成器的代码:
def reverse_binary_search(a, threshold):
lo = 0
for t in threshold:
if lo < 0:
raise ValueError('lo must be non-negative')
hi = len(a)
while lo < hi:
mid = (lo+hi)/2
if t > a[mid][6]:
hi = mid
else:
lo = mid+1
yield lo
my_list = [[3,0.99,1], [2,0.98,54], [10,.85,4], [1,0.7,10], [12,0.69,31], [12,0.65,43], [1.56,0]]
threshold = [0.97, 0.90, 0.83, 0.6]
index_list = list(reverse_binary_search(my_list, threshold))