如何在已排序的 numpy 数组中查找小于给定标量的第一个元素

另请查看如何在已排序的 numpy 数组中查找大于给定标量的第一个元素

你可以像这样使用 np.searchsorted()

find_first_smaller.py
idx = np.searchsorted(arr, scalar, side='left')

完整示例:

find_first_smaller_example.py
import numpy as np

# 示例数组
arr = np.array([1, 2, 3, 4, 5])

# 我们将搜索此值
scalar = 3.5

# 使用 numpy.searchsorted() 查找数组中小于标量的第一个元素
idx = np.searchsorted(arr, scalar, side='left')

# 打印结果索引
print(idx)

Check out similar posts by category: Python