如何用Python旋转由列表构成的棋盘90度?
Hey there! Let's break down how to rotate your 4x4 chessboard 90 degrees (both clockwise and counterclockwise) — it's straightforward with Python's built-in tools, and I'll also show you the manual way to understand the underlying logic.
First, let's recap your current board for reference:
board = [[0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 2], [0, 3, 0, 0]]
1. Rotate 90 Degrees Clockwise
The easiest way to do this is using reversed() and zip() with a list comprehension. Here's the code:
# Rotate clockwise rotated_clockwise = [list(row) for row in zip(*reversed(board))] # Let's print the result to verify for row in rotated_clockwise: print(row)
Output:
[0, 1, 0, 0] [3, 0, 0, 0] [0, 0, 0, 0] [0, 0, 2, 0]
How it works:
reversed(board)flips the order of the board's rows (so we start from the bottom row up).zip(*reversed(board))transposes the flipped board (swaps rows with columns).- The list comprehension converts each tuple returned by
zip()into a list, giving us our rotated board.
If you prefer a manual approach (to see the coordinate transformation), you can use nested list comprehensions:
n = len(board) rotated_clockwise = [[board[n - 1 - j][i] for j in range(n)] for i in range(n)]
This follows the rule for clockwise rotation: the value at position (i, j) in the new board comes from (n-1-j, i) in the original board (where n is the size of the square board).
2. Rotate 90 Degrees Counterclockwise
If you ever need to rotate the other way, here's how:
# Rotate counterclockwise rotated_counterclockwise = [list(row) for row in reversed(list(zip(*board)))] # Or using manual list comprehension: # rotated_counterclockwise = [[board[j][n - 1 - i] for j in range(n)] for i in range(n)] # Print the result for row in rotated_counterclockwise: print(row)
Output:
[0, 0, 2, 0] [0, 0, 0, 0] [3, 0, 0, 0] [0, 1, 0, 0]
Bonus: Fixing Your Board Generation Function
I noticed your ctcb function was incomplete — here's a version that generates the board you provided from numlist = [1,3,0,2] (assuming the logic is: for each index i in numlist, if numlist[i] != 0, place the number i+1 at column numlist[i]-1 in row i):
def ctcb(numlist): # Create The Chess Board the_len = len(numlist) board = [[0]*the_len for _ in range(the_len)] # Initialize empty board for row_idx, col_val in enumerate(numlist): if col_val != 0: # Place row_idx+1 at (row_idx, col_val-1) (since columns are 0-indexed) board[row_idx][col_val - 1] = row_idx + 1 return board # Test it out numlist = [1,3,0,2] generated_board = ctcb(numlist) for row in generated_board: print(row)
Output:
[0, 0, 0, 0] [1, 0, 0, 0] [0, 0, 0, 2] [0, 3, 0, 0]
Perfect, that matches your original board!
内容的提问来源于stack exchange,提问作者Domenico Agosta

