如何从8x8列表指定元素提取对角线?Numpy offset使用遇阻
解决8×8矩阵中指定元素的对角线提取问题
问题描述
我需要从8×8列表中提取指定参考点对应的两条对角线:
- 左上到右下的对角线(如示例中3×5矩阵里以9为参考点,得到
[2,9,15]) - 右上到左下的对角线(如示例中得到
[5,9,13])
尝试用numpy.diagonal的offset参数实现,但无法正常工作,相关代码如下:
board_state = [ 'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', '', '', '', '', '', '', '', '', '', 'b2', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R' ] def diagonals(board_state): board_state = np.array(board_state) diagonals_lst = np.diagonal(board_state.reshape([8, 8]), offset=-1) # point of reference for now is b2
问题原因
numpy.diagonal的offset参数是相对于矩阵主对角线的偏移量,并非针对指定元素的位置。只有当目标元素恰好落在该偏移对应的对角线上时,才能得到正确结果,无法直接定位任意元素的对角线。
解决方案
要提取指定元素的两条对角线,核心是利用对角线的数学特征:
- 左上→右下对角线:所有元素的
行索引 - 列索引等于参考点的行索引 - 列索引 - 右上→左下对角线:所有元素的
行索引 + 列索引等于参考点的行索引 + 列索引
完整实现代码
import numpy as np board_state = [ 'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', '', '', '', '', '', '', '', '', '', 'b2', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R' ] def get_diagonals(board_state, target): # 将一维列表转为8×8矩阵 board = np.array(board_state).reshape(8, 8) # 获取目标元素的行、列索引(假设棋盘上目标唯一) row_indices, col_indices = np.where(board == target) if len(row_indices) == 0: return [], [] row, col = row_indices[0], col_indices[0] # 提取左上→右下对角线:行-列 = 定值 diag1 = board[np.indices(board.shape)[0] - np.indices(board.shape)[1] == row - col] # 提取右上→左下对角线:行+列 = 定值 diag2 = board[np.indices(board.shape)[0] + np.indices(board.shape)[1] == row + col] # 转为普通列表返回 return diag1.tolist(), diag2.tolist() # 测试:提取元素'b2'的两条对角线 diag_top_left_to_bottom_right, diag_top_right_to_bottom_left = get_diagonals(board_state, 'b2') print("左上到右下对角线:", diag_top_left_to_bottom_right) print("右上到左下对角线:", diag_top_right_to_bottom_left)
输出结果
左上到右下对角线: ['', 'b2', '', '', 'P', 'B'] 右上到左下对角线: ['k', 'p', '', 'b2', '']
内容的提问来源于stack exchange,提问作者Rishit Sharma
相关产品推荐
相关产品推荐

