[英]How to diagonally split a matrix in four parts?
這不是最佳解決方案,但它正在工作:
def index_is_top(index_c, index_r, c, r):
return r < index_r and ((c <= index_c and index_c - c <= index_r - r) or (c > index_c and c - index_c < index_r - r))
def index_is_bottom(index_c, index_r, c, r):
return r > index_r and ((c >= index_c and index_c - c >= index_r - r) or (c < index_c and c - index_c > index_r - r))
def index_is_left(index_c, index_r, c, r):
return c < index_c and ((r < index_r and index_r - r < index_c - c) or (r >= index_r and r - index_r <= index_c - c))
index_c, index_r = (1, 2)
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
tmp = [list(zip(l, range(len(l)))) for l in matrix]
tmp = zip(tmp, range(len(tmp)))
matrix_with_indices = [(n, c, r) for (sublist, r) in tmp for (n, c) in sublist]
# if you are deleting items from the matrix during these steps, then you can skip the "n not in top/bottom/left" checks
top = [n for (n, c, r) in matrix_with_indices if (index_is_top(index_c, index_r, c, r))]
bottom = [n for (n, c, r) in matrix_with_indices if (n not in top and index_is_bottom(index_c, index_r, c, r))]
left = [n for (n, c, r) in matrix_with_indices if (n not in top and n not in bottom and index_is_left(index_c, index_r, c, r))]
right = [n for (n, c, r) in matrix_with_indices if ((c != index_c or r != index_r) and n not in top and n not in bottom and n not in left)]
print(list(top))
print(list(left))
print(list(bottom))
print(list(right))
>> [1, 2, 3, 5, 6]
>> [9, 13]
>> [14, 15]
>> [4, 7, 8, 11, 12, 16]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.