简体   繁体   English

numpy.unique生成一个独特的列表在哪方面?

[英]numpy.unique generates a list unique in what regard?

If you input an array with general objects to numpy.unique , the result will be unique based upon what? 如果你输入一个带有一般对象的数组到numpy.unique ,那么结果将是什么?

I have tried: 我试过了:

import numpy as np

class A(object): #probably exists a nice mixin for this :P
    def __init__(self, a):
        self.a = a
    def __lt__(self, other):
        return self.a < other.a
    def __le__(self, other):
        return self.a <= other.a
    def __eq__(self, other):
        return self.a == other.a
    def __ge__(self, other):
        return self.a >= other.a
    def __gt__(self, other):
        return self.a > other.a
    def __ne__(self, other):
        return self.a != other.a
    def __repr__(self):
        return "A({})".format(self.a)
    def __str__(self):
       return self.__repr__()

np.unique(map(A, range(3)+range(3)))

which returns 返回

array([A(0), A(0), A(1), A(1), A(2), A(2)], dtype=object)

but my intentions are to get: 但我的意图是得到:

array([A(0), A(1), A(2)], dtype=object)

Assuming the duplicate A(2) is a typo, I think you simply need to define __hash__ (see the docs ): 假设重复的A(2)是拼写错误,我认为你只需要定义__hash__ (参见文档 ):

import numpy as np
from functools import total_ordering

@total_ordering
class A(object):
    def __init__(self, a):
        self.a = a
    def __lt__(self, other):
        return self.a < other.a
    def __eq__(self, other):
        return self.a == other.a
    def __ne__(self, other):
        return self.a != other.a
    def __hash__(self):
        return hash(self.a)
    def __repr__(self):
        return "A({})".format(self.a)
    def __str__(self):
       return repr(self)

produces 产生

>>> map(A, range(3)+range(3))
[A(0), A(1), A(2), A(0), A(1), A(2)]
>>> set(map(A, range(3)+range(3)))
set([A(0), A(1), A(2)])
>>> np.unique(map(A, range(3)+range(3)))
array([A(0), A(1), A(2)], dtype=object)

where I've used total_ordering to reduce the proliferation of methods, as you guessed was possible. 正如你猜测的那样,我已经使用了total_ordering来减少方法的扩散。 :^) :^)

[Edited after posting to correct missing __ne__ .] [在发布后编辑以纠正缺失的__ne__ 。]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM