在 Python 中查找非重叠子矩阵
Finding Non-Overlapping Sub Matrices in Python
非重叠子矩阵
我一直在寻找一种方法来仅获取非重叠子矩阵。
我下面的代码找到了所有的子矩阵。
代码:
n = 4
matrix = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
k = 2 #Finding 2x2 submatrices
t=[]
for i in range(n-k+1):
for j in range(n-k+1):
l=[]
for x in range(i,i+k):
for y in range(j,j+k):
if x==i or x==i+k-1 or y==j or y==j+k-1:
l.append(matrix[x][y])
t.append(l)
所以如果我打印 t
我得到:
for i in t:
print(i)
O/P:
[1, 2, 5, 6]
[2, 3, 6, 7]
[3, 4, 7, 8]
[5, 6, 9, 10]
[6, 7, 10, 11]
[7, 8, 11, 12]
[9, 10, 13, 14]
[10, 11, 14, 15]
[11, 12, 15, 16]
但是我想要的o/p是:
[1,2,5,6]
[3,4,7,8]
[9,10,13,14]
[11,12,15,16]
当您循环遍历 range(n-k+1)
中的元素时,您正在使用参数 start=0、stop 调用 range
=n-k+1=3,step=1,得到数组[0, 1, 2]
。以此为出发点是个问题。
为确保您的结果仅包含互斥元素,请将 step 参数更改为 k:
In [7]: t = []
...: for i in range(0, n, k):
...: for j in range(0, n, k):
...: t.append([
...: matrix[i+ii][j+jj]
...: for ii in range(k) for jj in range(k)])
In [8]: t
[[1, 2, 5, 6], [3, 4, 7, 8], [9, 10, 13, 14], [11, 12, 15, 16]]
非重叠子矩阵
我一直在寻找一种方法来仅获取非重叠子矩阵。 我下面的代码找到了所有的子矩阵。
代码:
n = 4
matrix = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
k = 2 #Finding 2x2 submatrices
t=[]
for i in range(n-k+1):
for j in range(n-k+1):
l=[]
for x in range(i,i+k):
for y in range(j,j+k):
if x==i or x==i+k-1 or y==j or y==j+k-1:
l.append(matrix[x][y])
t.append(l)
所以如果我打印 t
我得到:
for i in t:
print(i)
O/P:
[1, 2, 5, 6]
[2, 3, 6, 7]
[3, 4, 7, 8]
[5, 6, 9, 10]
[6, 7, 10, 11]
[7, 8, 11, 12]
[9, 10, 13, 14]
[10, 11, 14, 15]
[11, 12, 15, 16]
但是我想要的o/p是:
[1,2,5,6]
[3,4,7,8]
[9,10,13,14]
[11,12,15,16]
当您循环遍历 range(n-k+1)
中的元素时,您正在使用参数 start=0、stop 调用 range
=n-k+1=3,step=1,得到数组[0, 1, 2]
。以此为出发点是个问题。
为确保您的结果仅包含互斥元素,请将 step 参数更改为 k:
In [7]: t = []
...: for i in range(0, n, k):
...: for j in range(0, n, k):
...: t.append([
...: matrix[i+ii][j+jj]
...: for ii in range(k) for jj in range(k)])
In [8]: t
[[1, 2, 5, 6], [3, 4, 7, 8], [9, 10, 13, 14], [11, 12, 15, 16]]