我以for循环的递增顺序遍历矩阵以找到非零元素的左上角索引,并获得非零元素的右下角索引我遍历for循环的递减顺序。
代码如下:
import numpy as np
A= np.array([
[0, 7, 7, 0, 0, 0, 0, 0, 0],
[0, 7, 7, 0, 0, 9, 0, 0, 0],
[0, 7, 7, 0, 0, 9, 0, 0, 0],
[0, 7, 7, 0, 0, 9, 0, 0, 0],
[0, 7, 7, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[6, 6, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 5, 5, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]])
def getting_top_left_indexes(A):
break_condition = False
M,N = A.shape
pos = []
for i in range(M):
if break_condition == True:
break
for j in range(N):
if A[i,j]!=0:
pos.append((i,j,A[i,j]))
break_condition = True
break
return pos
def getting_bottom_right_indexes(A):
break_condition = False
M,N = A.shape
pos = []
for i in range(M-1, 0, -1):
if break_condition == True:
break
for j in range(N-1, 0, -1):
if A[i,j]!=0:
pos.append((i,j,A[i,j]))
break_condition = True
break
return pos
top_left_indexes = getting_top_left_indexes(A)
bottom_right_indexes = getting_bottom_right_indexes(A)
编辑:我编辑了关于您的解释的答案。
这里更新的代码:
import numpy as np
A= np.array([
[0, 7, 7, 0, 0, 0, 0, 0, 0],
[0, 7, 7, 0, 0, 9, 0, 0, 0],
[0, 7, 7, 0, 0, 9, 0, 0, 0],
[0, 7, 7, 0, 0, 9, 0, 0, 0],
[0, 7, 7, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[6, 6, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 5, 5, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]])
def get_indexes(A):
M,N = A.shape
pos = []
for i in range(M):
for j in range(N):
if A[i, j] != 0:
pos.append((i,j,A[i,j]))
return pos
def filtering_indexes(indexes):
filtered_list = []
sorted_indexes = sorted(indexes, key=lambda x: x[-1])
top_left_index = sorted_indexes[0]
for i in range(0, len(sorted_indexes)):
if sorted_indexes[i][2] == top_left_index[2]:
pass
else:
filtered_list.append(sorted_indexes[i-1])
top_left_index = sorted_indexes[i]
filtered_list.append(top_left_index)
if sorted_indexes[i][2] == top_left_index[2]:
filtered_list.append(sorted_indexes[i])
return filtered_list
indexes = get_indexes(A)
filtered_indexes = filtering_indexes(indexes)