查找给定数字在分区中的位置

Finding where a given number falls in a partition

假设我有一个排序的整数数组说

partition = [0, 3, 7, 12, 18, 23, 27]

然后给定一个值

value = 9

我想 return 我的价值所在的区间。例如

bounds = function(partition, value)
print(bounds)
>>>[7,12]

是否有可以帮助我的功能,或者我是否必须从头开始构建它?

尝试numpy.searchsorted().来自纪录片:

Find indices where elements should be inserted to maintain order.

import numpy as np
partition = np.array( [0, 3, 7, 12, 18, 23, 27] )
value = 9
idx = np.searchsorted(partition,value)
bound = (partition[idx-1],partition[idx])
print(bound)
>>>>(7,12)

searchsorted的优点是它可以一次为您提供多个值的索引。

bisect module 非常适合高效地执行此操作。它将 return 上界的索引。

如果值超出范围,您需要进行一些错误检查:

from bisect import bisect
partition = [0, 3, 7, 12, 18, 23, 27]
value = 9
top = bisect(partition, value)

print(partition[top-1], partition[top])
# 7 12
 def function(partition,value):
  for i in range(len(partition)):
  if partition[i]<value and partition[i+1]>value:
    print [partition[i],partition[i+1]]
 partition = [0, 3, 7, 12, 18, 23, 27,5,10]
 value=9
 function(partition,value)