python - 为什么我的脚本会引发TypeError : 'int' object is not subscriptable

标签 python syntax-error

我写了一个脚本,将矩阵顺时针旋转90度。我想通了
淘汰算法,但坚持执行。

def rotate(M):
    #Let M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    n = len(M)
    temp = None
    for i in range(0, n):
        for j in range(i, n):
            temp = M[i][j]
            M[i][j] = M[j][i]
            M[j][i] = temp
    nby2 = int(n / 2)
    #error loop
    for j in range(0, nby2):
        for i in range(0, n):
            temp = M[i][j]          
            M[i][j] = M[i][n - 1 - j]
            M[i][n - 1 -j] = temp
            #print(M[i][j], M[i][n - 1 - j])

    for i in M:
        print(i)

temp = M[i][j]正在提高TypeError: 'int' object is not subscriptable尽管print语句在错误循环中返回没有错误的矩阵元素,并且上述循环工作得很好。

最佳答案

这是正确的灵魂:

def rotate(M):
    #Let M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    n = len(M)
    temp = None
    for i in range(0, n):
        for j in range(i, n):
            temp = M[i][j]
            M[i][j] = M[j][i]
            M[j][i] = temp
    nby2 = int(n / 2)
    #error loop
    print(M, nby2)
    for j in range(0, nby2):
        for i in range(0, n):
            temp = M[i][j]          
            M[i][j] = M[i][n - 1 - j]
            M[i][n - 1 -j] = temp
            #print(M[i][j], M[i][n - 1 - j])

    for i in M:
        print(i)

注意M[n - 1 -j][i] = temp行中的错误。您忘记添加第二个索引,因此导致列表被整数替换。

关于python - 为什么我的脚本会引发TypeError : 'int' object is not subscriptable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46048951/

相关文章:

python - 使用按钮时 tuplex 超出范围

syntax-error - 用微比特在mu上编码时的语法错误

mysql语法错误无法弄清楚

python - Python : SyntaxError

python - beautifulsoup 和 request.post

python - 如何使用 R 获取过去几年的高音扬声器数据?

c++ - 来自另一个类的 switch 语句中的 static const int 导致错误 C2051 : case expression not constant

python - 使用 argv 时出错

python - 无法从 Eclipse 运行/调试 Django 的 manage.py

python - 如何在 keras 生成器中使用 numpy memmap 不超过 RAM 内存?