【问题标题】:Can I find out if one numpy vector appears as a slice of another?我可以找出一个 numpy 向量是否显示为另一个向量的切片吗?
【发布时间】:2020-05-16 23:29:32
【问题描述】:

我想知道我的 numpy 向量 needle 是否作为切片或连续子向量出现在另一个向量 haystack 中。

我想要一个函数 find(needle, haystack) 当且仅当存在可能的整数索引 pq 使得 needle 等于 haystack[p:q] 时返回 true,其中"equals" 表示元素在所有位置都相等。

例子:

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 向量(一维数组)。

对于 Python 中的字符串,等价的操作很简单:in:"bcd" in "abcde" == True


关于维度的附录。

亲爱的读者,您可能会被类似的问题所吸引,例如testing whether a Numpy array contains a given rowChecking if a NumPy array contains another array。但是我们可以忽略这种相似性,因为考虑到维度并没有帮助。

向量是一维数组。在numpy 术语中,长度为N 的向量将具有.shape == (N,);它的形状长度为 1。

其他参考的问题是,通常寻求为二维矩阵中的行找到精确匹配。

我正试图像窗户一样沿着我的一维 干草堆 的同一轴滑动我的一维 needle,直到整个 needle em> 匹配通过窗口可见的 haystack 部分。

【问题讨论】:

标签: python numpy numpy-ndarray


【解决方案1】:

如果您可以创建两个数组的副本,您可以使用 Python in 字节对象运算符:

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

【讨论】:

  • 这太机智了。
【解决方案2】:

尝试使用列表理解:

def find(a,x):
    return any([x[i:i+len(a)]==a for i in range(1+len(x)-len(a))])

输出:

print(find([2,3,4], [1,2,3,4,5]),
find([2,4], [1,2,3,4,5]),
find([2,3,4], [0,1,2,3]), find([2,3,4], [0,1,2,3,4,5,2,3,4]))
>> True False False True

【讨论】:

  • 是的,这是我采用的方法。我宁愿希望有一个我没有找到的现有功能。
猜你喜欢
  • 1970-01-01
  • 2019-11-13
  • 2021-12-06
  • 2013-08-12
  • 1970-01-01
  • 2017-02-14
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多