定义
An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method), and can be compared to other objects (it needs an eq() method).
判别
- 内建对象
- hashable
- tuple,字符串,frozenset
- not hashable
- list,dictionaries
- hashable
- 用户定义的对象
- 默认是hashable的
用处
- 作为字典的key值
- 作为set的元素
应用
给定一个二维数组arr,arr中每个元素是一个一维的数组,去除其重复的一维数组
In [48]: arr = np.array([num[:3],num[:3],num[1:4]])
In [49]: arr
Out[49]:
array([[0, 1, 2],
[0, 1, 2],
[1, 2, 3]])
In [50]: tmp = set([tuple(t) for t in arr])
In [51]: tmp
Out[51]: {(0, 1, 2), (1, 2, 3)}
set的构造函数:class set([iterable])
要求iterable内的所有元素都是hashable的
利用列表表达式生成一个列表,但是列表内默认的元素是可变的(not hashable),所以需要强制转换成tuple类型
Alternative solution
In[53]: np.unique(arr,axis=0)
Out[53]:
array([[0, 1, 2],
[1, 2, 3]])