簡體   English   中英

如何將矩陣對角分割成四部分?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM