You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python网格顺时针旋转90度代码异常原因排查

Why Your Grid Rotation Code Isn't Working as Expected

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:12:40