You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将表示棋盘位置的元组转换为二维数组?

棋盘棋子位置转二维数组问题

给定一个N×N棋盘,元组t=(0,3,2,1)中,元素的索引代表列,元素值代表从底部开始计数的行(0为最底行)。以示例为例:

  • 第0列棋子在最底行(行0)
  • 第1列棋子在最高行(行3)
  • 第2列棋子在从底部数第三行(行2)
  • 第3列棋子在从底部数第二行(行1)

需要将其转换为如下二维数组(数组行索引0为顶部,N-1为底部):

[[0,1,0,0],
 [0,0,1,0],
 [0,0,0,1],
 [1,0,0,0]]

你已经写出了数组框架代码:

pieces_locations = (0,3,2,1)
pieces_locations = list(pieces_locations)

table_size = len(pieces_locations)

arr = [[0 for col in range(table_size)] for row in range(table_size)]

解决方法

核心是把「从底部开始的行值」转换为数组的「从顶部开始的行索引」,转换公式为:数组行索引 = table_size - 1 - 原行值。

比如示例中table_size=4:

  • 原行0(最底行)→ 4-1-0=3(数组第3行,最底部)
  • 原行3(最顶行)→4-1-3=0(数组第0行,最顶部)

基于这个转换,遍历每一列找到对应数组行位置赋值为1即可,完整代码如下:

pieces_locations = (0,3,2,1)
table_size = len(pieces_locations)

# 初始化全0数组
arr = [[0 for _ in range(table_size)] for _ in range(table_size)]

# 遍历每一列,赋值棋子位置
for col in range(table_size):
    original_row = pieces_locations[col]
    arr_row = table_size - 1 - original_row
    arr[arr_row][col] = 1

# 输出结果
for row in arr:
    print(row)

运行后会输出目标二维数组:

[0, 1, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 1]
[1, 0, 0, 0]

内容的提问来源于stack exchange,提问作者Saleh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:16:13