我可以找出一个 numpy 向量是否显示为另一个向量的一部分吗? [英] Can I find out if one numpy vector appears as a slice of another?
问题描述
我想知道我的 numpy 向量 needle
是否作为切片或连续子向量出现在另一个向量 haystack
中.
I want to find out if my numpy vector, needle
, appears inside another vector, haystack
, as a slice, or contiguous sub-vector.
我想要一个函数 find(needle, haystack)
当且仅当存在可能的整数索引 p 和 q 时返回 trueneedle
等于 haystack[p:q]
,其中equals"表示元素在所有位置都相等.
I want a function find(needle, haystack)
that returns true if and only if there are possible integer indexes p and q such that needle
equals haystack[p:q]
, where "equals" means elements are equal at all positions.
示例:
find([2,3,4], [1,2,3,4,5]) == True
find([2,4], [1,2,3,4,5]) == False # not contiguous inside haystack
find([2,3,4], [0,1,2,3]) == False # incomplete
这里我使用列表来简化说明,但实际上它们将是 numpy 向量(一维数组).
Here I am using lists to simplify the illustration, but really they would be numpy vectors (1-dimensional arrays).
对于 Python 中的字符串,等效操作很简单:它是 in
: "bcd" in "abcde" == True
.
For strings in Python, the equivalent operation is trivial: it's in
: "bcd" in "abcde" == True
.
关于维度的附录.
亲爱的读者,您可能会被类似的问题所吸引,例如 测试 Numpy 数组是否包含给定的行,或 检查一个 NumPy 数组是否包含另一个数组.但是我们可以认为这种相似性对维度的考虑没有帮助.
Dear reader, you might be tempted by similar looking questions, such as testing whether a Numpy array contains a given row, or Checking if a NumPy array contains another array. But we can dismiss this similarity as not being helpful by a consideration of dimensions.
向量是一维数组.在 numpy
术语中,长度为 N 的向量将具有 .shape == (N,)
;其形状的长度为 1.
A vector is a one-dimensional array. In numpy
terms a vector of length N will have .shape == (N,)
; its shape has length 1.
其他引用的问题是,通常寻求为二维矩阵中的行找到精确匹配.
The other referenced questions are, generally seeking to find an exact match for a row in a matrix that is 2-dimensional.
我试图像窗户一样沿着一维干草堆的同一轴滑动我的一维针,直到整个针em> 匹配通过窗口可见的 haystack 部分.
I am seeking to slide my 1-dimensional needle along the same axis of my 1-dimensional haystack like a window, until the entire needle matches the portion of the haystack that is visible through the window.
推荐答案
如果您可以创建两个数组的副本,那么您可以使用 Python in
运算符来处理字节对象:>
If you are fine with creating copies of the two arrays, you could fall back on Python in
operator for byte objects:
def find(a, b):
return a.tobytes() in b.tobytes()
print(
find(np.array([2,3,4]), np.array([1,2,3,4,5])),
find(np.array([2,4]), np.array([1,2,3,4,5])),
find(np.array([2,3,4]), np.array([0,1,2,3])),
find(np.array([2,3,4]), np.array([0,1,2,3,4,5,2,3,4])),
)
# True False False True
这篇关于我可以找出一个 numpy 向量是否显示为另一个向量的一部分吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!