纽比。独一无二举止怪异数字阵列对象的

2024-09-28 22:01:09 发布

您现在位置:Python中文网/ 问答频道 /正文

此问题与“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的预期行为:

^{pr2}$

这没问题,很管用。但这并不像预期的那样有效:

>>> 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>}


Tags: importselfnumpyreturnobjectdefnparray
1条回答
网友
1楼 · 发布于 2024-09-28 22:01:09

通过np.unique的源代码,似乎实际执行的分支是

else:
    ar.sort()
    flag = np.concatenate(([True], ar[1:] != ar[:-1]))
    return ar[flag]

它简单地对这些项进行排序,然后取与前一项不相等的项。但这不管用吗?。。哎呀。这是我请客。您的原始代码定义了__ne__,我在删除total_ordering-ed的比较时意外地删除了它

^{pr2}$

__ne__放回:

>>> UniqueObject(1) != UniqueObject(1)
False
>>> np.array(map(UniqueObject, [1,1,2,2]))
array([UniqueObject(1), UniqueObject(1), UniqueObject(2), UniqueObject(2)], dtype=object)
>>> np.unique(np.array(map(UniqueObject, [1,1,2,2])))
array([UniqueObject(1), UniqueObject(2)], dtype=object)

相关问题 更多 >