我怎么能表示元组作为一个二维数组在python?



想象一个NxN棋盘,我有一个元组t = (0,3,2,1),它代表每列的棋子位置(col = index),每个数字代表一行,从底部0开始。

在这个例子中,它有4列,第一部分在行=0(最底行),第二部分在行=3(第四/最高行),第三部分在行=2(倒数第三行),第四部分在倒数第二行。

我想把它表示成一个二维数组,如下所示:

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

我可以使用以下代码生成2D数组

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)]

但是,我无法将1分配到正确的位置。

我能够理解这个:arr[row][col],但是行是颠倒的(0是顶部到N是底部)。

在制作列表(0的矩阵)之后使用这个**如果位置列表不像行数那么长,程序将崩溃(使用try和except来计数)

for x, i in enumerate(range(1, len(arr))):
arr[-i][pieces_locations[x]] = 1

这应该会给你想要的输出,我希望这对你有帮助

首先创建二维零列表

arr = [[0] * table_size for _ in range(table_size)]

然后遍历位置,用1替换适当的元素。

for col, row in enumerate(pieces_location, 1):
arr[-row][col] = 1

我能算出来,虽然我相信有一个更方便的方法。

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)]

for row in range(0, table_size):
arr[row][pieces_locations.index(row)] = 1

res = arr[::-1]
print (res)

最新更新