我python中list不能做索引

2026-01-26 13:25:11

先看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 "", line 1, in

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