我是Python 3中的新手。我想要做的是在类中重写一个函数,但是当我运行它时。我收到了这个错误:
<ipython-input-67-42b4fc5729b3> in savage(self) 11 list1 = list() 12 while i < len(self.Acciones): ---> 13 self.test3 = [self.MatPagos - self.test2 for self.MatPagos, self.test2 in zip(self.test2,self.MatPagos[0])] 14 list1.append(self.test3) 15 i += 1 TypeError: 'int' object is not subscriptable
这是功能,它运行得很完美:
def Savage(Acciones,MatPagos):
test = [list(x) for x in zip(*MatPagos)]
test2 = [max(k) for k in test]
i = 0
list1 = list()
while i < len(Acciones):
test3 = [MatPagos - test2 for MatPagos, test2 in zip(test2,MatPagos[i])]
list1.append(test3)
i += 1
MatPagos = list1
这给了我这个结果:
[[0, 0, 3200, 8600], [1200, 1200, 0, 3200], [2400, 2400, 1200, 0]]
这是我为班级重写它的方式:
class savage_c(wald):
def savage(self):
super().getMatPagos()
self.test = [list(x) for x in zip(*self.MatPagos)]
self.test2 = [max(k) for k in self.test]
i = 0
list1 = list()
while i < len(self.Acciones):
self.test3 = [self.MatPagos - self.test2 for self.MatPagos, self.test2 in zip(self.test2,self.MatPagos[i])]
list1.append(self.test3)
i += 1
self.MatPagos = self.list1
print(self.MatPagos)
这些是可变内容:
print(self.MatPagos)
>>> [[200, 3200, 1800, -1800], [-1000, 2000, 5000, 3600], [-2200, 800, 3800, 6800]]
print(self.test)
>>> [[200, -1000, -2200], [3200, 2000, 800], [1800, 5000, 3800], [-1800, 3600, 6800]]
print(self.test2)
>>> [200, 3200, 5000, 6800]
我错过了什么?
答案 0 :(得分:0)
@ 0x5453你在哪里,但我无法想象它。
我在Stack西班牙语版本中获得了answer @FJSevilla:
您不应将该属性用作列表推导中的内部变量。当你这样做时:
self.test3 = [self.MatPagos - self.test2 for self.MatPagos, self.test2 in zip(self.test2, self.MatPagos[i])]
您覆盖属性self.MatPagos
和self.test2
的值,其方式是在第二次迭代中都是整数而不是初始列表。做类似的事情:
self.test3 = [matP - test2 for matP, test2 in zip(self.test2, self.MatPagos[i])]
我建议您尽可能使用for
。它更“pythonic”,更有效率。如果您遍历self.MatPagos
的所有行,它将是:
def savage(self):
self.test = [list(x) for x in zip(*self.MatPagos)]
self.test2 = [max(k) for k in self.test]
self.MatPagos = [[matP - test2 for matP, test2 in zip(self.test2, mprow)] for mprow in self.MatPagos]