Python debug——TypeError: unhashable type(list/set/dict)

本文详细解释了Python中哈希的原理,特别是针对list、set、dict等数据结构为何不可哈希,以及如何正确地使用可哈希的数据类型如int、float、str、tuple等。此外还介绍了哈希在集合和字典中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正如错误提示,list/set/dict 均不可被哈希。

这一异常通常出现在,调用 set(…) 来构造一个 set (集合类型)时,set() 需要传递进来可哈希的元素(hashable items)。

  • (1)list、set、dict:是不可哈希的

    >>> list.__hash__
    None
    >>> set.__hash__
    None
    >>> dict.__hash__
    None
  • (2)int、float、str、tuple:是可以哈希的

    >>> int.__hash__
    <slot wrapper '__hash__' of 'int' objects>
    >>> float.__hash__
    <slot wrapper '__hash__' of 'float' objects>
    >>> str.__hash__
    <slot wrapper '__hash__' of 'str' objects>
    >>> tuple.__hash__
    <slot wrapper '__hash__' of 'tuple' objects>
  • (3)list 不使用 hash 值进行索引,故其对所存储元素没有可哈希的要求;set / dict 使用 hash 值进行索引,也即其要求欲存储的元素有可哈希的要求。

    >>> set([[], [], []])
    TypeError: unhashable type: 'list'
    >>> set([{}, {}, {}])
    TypeError: unhashable type: 'dict'
    >>> set([set(), set(), set()])
    TypeError: unhashable type: 'set'
  • (4)dict 仅对键(key)有可哈希的要求,对值(value)无此要求

    >>> dict([[["zhangsan", "lisi"], 20]])
    TypeError: unhashable type: 'list'

注:可能你会问,set 不是可以接受 list,并将其转换为 set 吗?比如set([1, 2, 3]),注意,上文说的可哈希,不可哈希,是对可迭代类型(iterables)所存储元素(elements)的要求,[1, 2, 3]是可迭代类型,其存储元素的类型为int,是可哈希的,如果set([[1, 2], [3, 4]])[[1, 2], [3, 4]]list of lists(list 构成的 list)自然是可迭代的,但其元素为 [1, 2][3, 4]是不可哈希的。

为什么 list 是不可哈希的,而 tuple 是可哈希的

  • (1)因为 list 是可变的在它的生命期内,你可以在任意时间改变其内的元素值。

  • (2)所谓元素可不可哈希,意味着是否使用 hash 进行索引

  • (3)list 不使用 hash 进行元素的索引,自然它对存储的元素有可哈希的要求;而 set 使用 hash 值进行索引。

References

[1] TypeError : Unhashable type

2025-04-02 09:53:44,008 ERROR trial_runner.py:616 – Trial CQL_ExpertGuidedEnv_5492d_00001: Error processing event. Traceback (most recent call last): File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/tune/trial_runner.py”, line 586, in _process_trial results = self.trial_executor.fetch_result(trial) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/tune/ray_trial_executor.py”, line 609, in fetch_result result = ray.get(trial_future[0], timeout=DEFAULT_GET_TIMEOUT) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/_private/client_mode_hook.py”, line 47, in wrapper return func(*args, **kwargs) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/worker.py”, line 1456, in get raise value.as_instanceof_cause() ray.exceptions.RayTaskError(TypeError): ray::CQL.train_buffered() (pid=5516, ip=10.200.84.15) File “python/ray/_raylet.pyx”, line 480, in ray._raylet.execute_task File “python/ray/_raylet.pyx”, line 432, in ray._raylet.execute_task.function_executor File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/tune/trainable.py”, line 167, in train_buffered result = self.train() File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/agents/trainer.py”, line 529, in train raise e File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/agents/trainer.py”, line 515, in train result = Trainable.train(self) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/tune/trainable.py”, line 226, in train result = self.step() File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/agents/trainer_template.py”, line 157, in step evaluation_metrics = self._evaluate() File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/agents/trainer.py”, line 749, in _evaluate self._sync_weights_to_workers(worker_set=self.evaluation_workers) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/agents/trainer.py”, line 802, in sync_weights_to_workers worker_set.foreach_worker(lambda w: w.restore(ray.get(weights))) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/evaluation/worker_set.py”, line 164, in foreach_worker local_result = [func(self.local_worker())] File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/agents/trainer.py”, line 802, in <lambda> worker_set.foreach_worker(lambda w: w.restore(ray.get(weights))) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/evaluation/rollout_worker.py”, line 1014, in restore self.policy_map[pid].set_state(state) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/policy/torch_policy.py”, line 515, in set_state s, device=self.device) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/utils/torch_ops.py”, line 111, in convert_to_torch_tensor return tree.map_structure(mapping, x) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/tree/init.py”, line 435, in map_structure [func(*args) for args in zip(*map(flatten, structures))]) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/tree/init.py”, line 435, in <listcomp> [func(*args) for args in zip(*map(flatten, structures))]) File “/home/dwh/anaconda3/envs/egpo_a/lib/python3.7/site-packages/ray/rllib/utils/torch_ops.py”, line 105, in mapping tensor = torch.from_numpy(np.asarray(item)) TypeError: can’t convert np.ndarray of type numpy.object. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.
04-05
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值