3 回答
TA贡献1934条经验 获得超2个赞
试试numpy.searchsorted()。来自纪录片:
查找应插入元素以保持顺序的索引。
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是它可以一次为您提供多个值的索引。
TA贡献1719条经验 获得超6个赞
该对开模块是有效的这样做很好。它将返回上限的索引。
如果该值可能超出范围,您需要进行一些错误检查:
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
TA贡献1841条经验 获得超3个赞
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)
添加回答
举报