6

我正在使用 numpy 模块来检索二维数组中最大值的位置。但是这个二维数组由 MyObjects 组成。现在我得到错误:

TypeError:不可排序的类型:int() > MyObject()

我试图用这段代码覆盖 int 函数:

def int(self):
    return self.score

但这并不能解决我的问题。我是否必须将 MyObjects 的二维数组转换为整数的二维数组,我是否必须扩展 Integer 对象(如果这在 python 中是可能的)或者我可以用另一种方式覆盖这个 int() 函数吗?

[编辑]

完整的对象:

class MyObject:
def __init__(self, x, y, score, direction, match):
    self.x = x
    self.y = y
    self.score = score
    self.direction = direction
    self.match = match

def __str__(self):
    return str(self.score)

def int(self):
    return self.score

我称这个对象的方式:

 def traceBack(self):
    self.matrix = np.array(self.matrix)
    maxIndex = self.matrix.argmax()
    print(self.matrix.unravel_index(maxIndex))
4

2 回答 2

16

尝试使用

...
def __int__(self):
    return self.score
...

test = MyObject(0, 0, 10, 0, 0)
print 10+int(test)

# Will output: 20

在您的 MyObject 类定义中。

于 2013-05-22T14:32:51.550 回答
1

max函数采用key应用于元素的 a 。那就是你放的地方score

通常 :

a = max(my_list, key=score)
于 2013-05-22T14:26:23.643 回答