神经网络项目矩阵运算类调用报错:TypeError对象不可下标访问
解决TypeError: 'MatrixOperations' object is not subscriptable错误
核心问题分析
你的代码存在两个关键问题:
- 实例方法参数顺序错误:Python类的实例方法必须将
self作为第一个参数,你把matx放在了self前面,导致调用时参数传递完全混乱。 - 未实现
getColumn方法:代码中调用了self.getColumn但类里没有定义这个方法,即使参数问题修复后也会触发AttributeError。
参数顺序错误的具体影响
当执行mo.transpose(mat2)时,Python会自动把实例mo作为第一个参数传入方法。原方法定义transpose(matx,self)会把mo赋值给matx,把mat2赋值给self。此时方法里的matx[0]实际是在访问mo[0],而MatrixOperations实例不支持下标操作,所以抛出TypeError: 'MatrixOperations' object is not subscriptable。
修正方案
方案1:修复参数顺序并实现getColumn方法
class MatrixOperations: def __init__(self): pass # 实现getColumn方法,提取矩阵指定列 def getColumn(self, matx, col_idx): return [row[col_idx] for row in matx] # 调整参数顺序,self放在第一个位置 def transpose(self, matx): transMatx = [[0 for i in range(len(matx))] for j in range(len(matx[0]))] for i in range(len(matx[0])): transMatx[i] = self.getColumn(matx, i) return transMatx mo = MatrixOperations() mat2 = [[1, 4], [2, 5], [3, 6]] print(mo.transpose(mat2)) # 输出: [[1, 2, 3], [4, 5, 6]]
方案2:简化转置逻辑(无需额外方法)
利用Python内置的zip函数可以更简洁地实现矩阵转置,避免额外方法的定义:
class MatrixOperations: def __init__(self): pass def transpose(self, matx): # zip(*matx)会按列打包成元组,再转成列表 return [list(col) for col in zip(*matx)] mo = MatrixOperations() mat2 = [[1, 4], [2, 5], [3, 6]] print(mo.transpose(mat2)) # 输出: [[1, 2, 3], [4, 5, 6]]
内容的提问来源于stack exchange,提问作者off oof
相关产品推荐
相关产品推荐

