此问题与“numpy.unique generates a list unique in what regard?”有关(但不相同)
设置:
import numpy as np
from functools import total_ordering
@total_ordering
class UniqueObject(object):
def __init__(self, a):
self.a = a
def __eq__(self, other):
return self.a == other.a
def __lt__(self, other):
return self.a < other.a
def __hash__(self):
return hash(self.a)
def __str__(self):
return "UniqueObject({})".format(self.a)
def __repr__(self):
return self.__str__()
np.unique
的预期行为:
这没问题,很管用。但这并不像预期的那样有效:
>>> np.unique(np.array(map(UniqueObject, [1, 1, 2, 2])))
array([UniqueObject(1), UniqueObject(1), UniqueObject(2), UniqueObject(2)], dtype=object)
怎么了np.数组使用dtype=objects处理python objects=list的方式不同?在
即:
objs = map(UniqueObject, [1, 1, 2, 2])
np.unique(objs) != np.unique(np.array(objs)) #?
{cdm>
通过
np.unique
的源代码,似乎实际执行的分支是它简单地对这些项进行排序,然后取与前一项不相等的项。但这不管用吗?。。哎呀。这是我请客。您的原始代码定义了
^{pr2}$__ne__
,我在删除total_ordering
-ed的比较时意外地删除了它将
__ne__
放回:相关问题 更多 >
编程相关推荐