这个解决方案怎么样:
1)找出小数组右上左手元素在大数组中的所有位置。
2) 检查大数组中每个给定元素对应的切片是否与小数组完全相同。
假设切片的左上角元素是5,我们会在大数组中找到5的位置,然后检查大数组中5左下角的切片是否与小数组相同。
import numpy as np
a = np.array([[0,1,5,6,7],
[0,4,5,6,8],
[2,3,5,7,9]])
b = np.array([[5,6],
[5,7]])
b2 = np.array([[6,7],
[6,8],
[7,9]])
def check(a, b, upper_left):
ul_row = upper_left[0]
ul_col = upper_left[1]
b_rows, b_cols = b.shape
a_slice = a[ul_row : ul_row + b_rows, :][:, ul_col : ul_col + b_cols]
if a_slice.shape != b.shape:
return False
return (a_slice == b).all()
def find_slice(big_array, small_array):
upper_left = np.argwhere(big_array == small_array[0,0])
for ul in upper_left:
if check(big_array, small_array, ul):
return True
else:
return False
结果:
>>> find_slice(a, b)
True
>>> find_slice(a, b2)
True
>>> find_slice(a, np.array([[5,6], [5,8]]))
False