简体   繁体   English

如何在 python 中将元组表示为二维数组?

[英]how can I represent tuple as a 2D array in python?

Imagine a NxN chess board, I have a tuple t = (0,3,2,1) which represents chess pieces location at each column (col = index), and each number represents the row, starting at 0 from bottom.想象一个 NxN 棋盘,我有一个元组t = (0,3,2,1) ,它代表每一列的棋子位置(col = 索引),每个数字代表行,从底部的 0 开始。

For this example, it has 4 columns, first piece is at row=0 (bottom row), second piece is on row=3 (fourth/highest row), third piece is on row=2 (third row from bottom), fourth piece is on second row from bottom.对于这个例子,它有 4 列,第一块在 row=0(底行),第二块在 row=3(第四/最高行),第三块在 row=2(从底部数第三行),第四块一块是从底部开始的第二行。

I would like to represent it as a 2D array as follows:我想将其表示为二维数组,如下所示:

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

I was able to generate the 2D array using this code我能够使用此代码生成二维数组

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

However, I was not able to assign the 1's in their correct locations.但是,我无法将 1 分配到正确的位置。

I was able to understand this: arr[row][col], but the rows are inverted (0 is top to N is bottom).我能够理解这一点:arr[row][col],但是行是倒置的(0 是顶部,N 是底部)。

First create the 2-d list of zeroes.首先创建二维零列表。

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

Then loop over the locations, replacing the appropriate elements with 1 .然后遍历位置,用1替换适当的元素。

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

Use this after you've made the list (A matrix of 0s) ** If the locations list is not as long as the number of rows, the program will crash (use try and except to counter)在你制作列表后使用它(0 的矩阵)** 如果位置列表不与行数一样长,程序将崩溃(使用 try 和 except 来反击)

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

This should give you your desired output, I hope this helps这应该会为您提供所需的 output,希望对您有所帮助

I was able to figure it out, although I'm sure there is a move convenient way.我能够弄清楚,虽然我确信有一个移动方便的方法。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM