如何在由列表组成的面板中轮换结果?
How to rotate the results in a board made of lists?
我正在尝试学习如何使用 Python 进行编码,并且我尝试了这个练习,在这个练习中我必须将这个板旋转 90°,但我不知道如何做。感谢您的帮助。
numlist = [1,3,0,2]
board = [[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[0, 3, 0, 0]]
当它被赋予一个 numlist 时,我用它来打印一个 table:
def ctcb(numlist): # Create The Chess Board
n = 0
board = []
the_len = len(numlist)
for i in range(the_len): # create a list with nested lists
board.append([])
for n in range(the_len):
board[i].append(0) # fills nested lists with data
while n < len(board):
for x,y in enumerate(numlist):
board[y][x] = y
n += 1
# print(board)
for e in board:
print(e)
结果应该是这个:
board = [[0, 0, 2, 0],
[0, 0, 0, 0],
[0, 0, 0, 3],
[0, 1, 0, 0]]
我们可以使用 zip(*board)
转置棋盘,然后使用 reversed
得到该转置的反向。
board = [[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[0, 3, 0, 0]]
print([list(x) for x in reversed(list(zip(*board)))])
# [[0, 0, 2, 0], [0, 0, 0, 0], [0, 0, 0, 3], [0, 1, 0, 0]]
我正在尝试学习如何使用 Python 进行编码,并且我尝试了这个练习,在这个练习中我必须将这个板旋转 90°,但我不知道如何做。感谢您的帮助。
numlist = [1,3,0,2]
board = [[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[0, 3, 0, 0]]
当它被赋予一个 numlist 时,我用它来打印一个 table:
def ctcb(numlist): # Create The Chess Board
n = 0
board = []
the_len = len(numlist)
for i in range(the_len): # create a list with nested lists
board.append([])
for n in range(the_len):
board[i].append(0) # fills nested lists with data
while n < len(board):
for x,y in enumerate(numlist):
board[y][x] = y
n += 1
# print(board)
for e in board:
print(e)
结果应该是这个:
board = [[0, 0, 2, 0],
[0, 0, 0, 0],
[0, 0, 0, 3],
[0, 1, 0, 0]]
我们可以使用 zip(*board)
转置棋盘,然后使用 reversed
得到该转置的反向。
board = [[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[0, 3, 0, 0]]
print([list(x) for x in reversed(list(zip(*board)))])
# [[0, 0, 2, 0], [0, 0, 0, 0], [0, 0, 0, 3], [0, 1, 0, 0]]