python - 如何查找列表中给定值的所有下限值和上限值

标签 python numpy bisect

  • 我有一个如下所示的数组:[1,2,4,1,2,5,1,2,6]
  • 给定值 3
  • 我想在上面的列表中找到封装给定值的所有值对。 IE; [2,4];[2,5];[2,6]

我可以使用二分法找到 [2,6] 值,但如何找到所有值?

x = np.array([1,2,4,1,2,5])
xL = bisect_left(x,start)-1
xU = bisect_left(x,start)
print(xL ," ", xU)
lower = x[xL]
upper = x[xU]
print(lower, upper)

附言 我的实际数据非常大,所以我不认为自己用 for 循环等编写代码是一种有效的方法,所以我想主要使用 pandas 等库中的构建。

最佳答案

你可以这样做:

import numpy as np


x = np.array([1, 2, 4, 1, 2, 5, 1, 2, 6])

x_left = x[:-1]
x_right = x[1:]

encapsulation = np.where((x_left < 3) & (x_right > 3))
left_encapsulation_values = x_left[encapsulation]
right_encapsulation_values = x_right[encapsulation]

您有一个用于左值的数组(不包含最后一个元素,因为它没有右邻居)和一个用于右值的数组(没有第一个元素,相同的想法)。然后你用你定义的条件屏蔽那些数组,瞧你有封装 3 的左右值。

left_encapsulation_values=array([2, 2, 2])
right_encapsulation_values=array([4, 5, 6])

关于python - 如何查找列表中给定值的所有下限值和上限值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73065816/

相关文章:

python - 按第一行对 numpy 2d 数组进行排序,维护列

python - 将文本文件解析为表格数据进行处理

带有 SELinux 的 Python MySQLdb

python - 在 python 中将字符串转换为数组的最快方法是什么?

python - Numpy:如何为不同索引的数组的每一列设置column[index:]=value?

git - 在 git bisect run 期间运行两个命令

python - 一分为二并列出用户定义的对象 (python 3)

python - 通过 int 选择 numpy 数组轴

python - 如何将特定的 C 模块移植到 Python 3?