TypeError: 'int' object is not subscriptable (python)

TypeError: 'int' object is not subscriptable (python)

我在 python3 中制作矩阵乘法算法时遇到问题。

这是代码:

def matrixMult(m1, m2):
    result = [[0 for x in range(len(m1))] for x in range(len(m2[0]))]
    # Iterate through rows of m1.
    for i in range(len(m1)):
        # Iterate through columns of m2.
        for j in range(len(m2[0])):
            # Iterate through rows of m2.
            for k in range(len(m2)):
                result[i][j] += m1[i][k] * m2[k][j]   # error occurs here.

    return result

像这样在两个随机矩阵上调用它:

m = [3, 4, 2]
n = [[13, 9, 7, 15], [8, 7, 4, 6], [6, 4, 0, 3]]
r = matrixMult(m, n)

这会产生 TypeError: 'int' object is not subscriptable 消息。

我为上面声明的两个矩阵添加了一个print(type()),它们是class 'list'。对函数原型 class 'list' 中使用的 classes 执行相同的操作。见鬼,一切都是 'list' 类型。我不知道 int object 是什么。

您正在将 m1 视为整数的嵌套列表:

result[i][j] += m1[i][k] * m2[k][j]
#               ^^^^^^^^

不是;它只是一个简单的整数列表。 m1[i] 然后是一个整数对象,你不能索引整数:

>>> [3, 4, 2][0]
3
>>> [3, 4, 2][0][0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

您可能想使用 just i 作为索引:

result[i][j] += m1[i] * m2[k][j]

或者只传入二维数组(所以传入[[3], [4], [2]]而不是[3, 4, 2])。

您有以下索引操作

m1[i][k]

但是 m1 被传入为

m = [3, 4, 2]

它只有 1 个索引维度,而不是 2 个维度。