a = np.array([1, 2, 2, 3])
print(np.searchsorted(a, 0)) # 0
print(np.searchsorted(a, 1)) # 0
print(np.searchsorted(a, 2)) # 1
print(np.searchsorted(a, 2, 'left')) # 1
print(np.searchsorted(a, 2, 'right')) # 3
print(np.searchsorted(a, 2.5, 'right')) # 3
print(np.searchsorted(a, 2.5, 'left')) # 3
print(np.searchsorted(a, 3, 'left')) # 3
print(np.searchsorted(a, 3, 'right')) # 4
print(np.searchsorted(a, 4)) # 4
print(np.searchsorted(a, [0, 1, 2, 3, 4, 5, ])) # [0 0 1 3 4 4]
searchsorted有三个重要参数:
- a:待查找的有序数组
- v:待查找的值
- side:字符串,取值为left或者right,表示取下界(闭区间)还是取上界(开区间),默认参数为下界闭区间
利用searchsorted可以非常炫酷地实现轮盘赌随机选取: