2013-05-05 52 views
3

如果你輸入一個帶有一般對象的數組到numpy.unique,結果會根據什麼來唯一嗎?numpy.unique在哪些方面生成一個唯一的列表?

我曾嘗試:

返回

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

,但我的意圖是獲得:

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

對不起,拼寫錯誤:P – SlimJim 2013-05-05 22:14:14

回答

4

假設重複A(2)是一個錯字,我覺得你根本需要定義__hash__(請參閱docs):

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) 

產生

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

,我已經使用total_ordering減少方法的擴散,你猜是可能的。 :^)

[發佈更正缺少__ne__編後]

+0

加入__hash__做到了,那麼什麼是一般物體的公式? 它首先檢查散列,如果散列是相同的,它會去__eq__? – SlimJim 2013-05-05 22:20:53

+0

我應該知道這一點,它已經太晚了,我不應該編碼:P – SlimJim 2013-05-05 22:21:37

+1

如果內存服務:第一個標識 - ''''= x = float(「nan」); len(set([x,x]))== 1',儘管'x!= x' - 然後它檢查哈希,如果那些不匹配,那麼它知道對象不能相等。如果哈希匹配,它會調用'__eq__'。例如,比較'np.unique([np.nan,np.nan])'與'np.unique([np.nan,float(「nan」)])''。 – DSM 2013-05-05 22:25:19