Python网格顺时针旋转90度代码异常原因排查
Let's walk through the problems in your code and fix them step by step:
1. Shallow Copy Causes Unintended Overwrites
The biggest issue here is your line rotatedGrid = grid[:]—this creates a shallow copy of the outer list. For 2D grids like yours, this means while rotatedGrid is a new outer list, each inner sublist still points directly to the same sublists in the original grid.
When you assign rotatedGrid[i][j] = grid[-(j+1)][i][:], you’re actually modifying the original grid’s elements at the same time. For example, when i=0 and j=0, you set rotatedGrid[0][0] to grid[2][0] (which is '7'), but since rotatedGrid[0] is the same list as grid[0], you’ve just changed grid[0][0] to '7' too. Later in the loop, when you try to access the original values from grid, they’ve already been overwritten—this is why you’re seeing repeated values like '7' and '4' in your output.
2. Minor Indexing Adjustment
While the shallow copy issue is the main culprit, your indexing logic has a small redundancy: the [i][:] at the end isn’t necessary (you’re copying a single immutable character, so slicing does nothing here). The correct mapping for a clockwise 90-degree rotation of an n x n grid is:rotatedGrid[i][j] = grid[n - 1 - j][i]
Where n is the length of the grid.
Fixed Code
Here’s the corrected version that addresses both problems:
def rotate90(grid): n = len(grid) # Create a completely new 2D list to avoid reference conflicts rotatedGrid = [[None for _ in range(n)] for _ in range(n)] for i in range(n): for j in range(n): # Correct index mapping for clockwise 90 rotation rotatedGrid[i][j] = grid[n - 1 - j][i] return rotatedGrid
Testing this with your input [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] will give you the expected output:[['7', '4', '1'], ['8', '5', '2'], ['9', '6', '3']]
This works because we build a brand new grid from scratch, so we never modify the original grid during the loop, and the index mapping correctly translates each position to its rotated spot.
内容的提问来源于stack exchange,提问作者HelloWorld4444

