python中list不能做索引


先看python中內置的list不能作為字典的key.

可將list或者ndarray轉化為tuple再做索引。

list不能進行hash:

import numpy as np
a1 = np.arange(3)
a2 = np.arange(3)
hash1 = hash(a1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

兩個ndarray轉為tuple后進行hash,所得的hash值是相同的

t1 = tuple(a1) t2 = tuple(a2)
hash1 = hash(t1)
hash2 = hash(t2)
print(hash1 == hash2)
True

 


更新…

a1 = [1,2,3]
h1 = hash(str(a1))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM