unhashable type: 'list' tuple
时间: 2023-07-24 12:02:28 浏览: 56
这个错误是因为你尝试使用一个不可哈希的类型作为字典的键。在Python中,字典的键必须是可哈希的类型,例如字符串、数字或元组。而列表是不可哈希的,因此不能作为字典的键。
如果你想使用列表作为字典的键,可以考虑将其转换为元组,因为元组是可哈希的。你可以使用`tuple()`函数将列表转换为元组,然后将其用作字典的键。例如:
```python
my_list = [1, 2, 3]
my_dict = {tuple(my_list): "value"}
```
这样就可以避免 "unhashable type: 'list'" 的错误了。
相关问题
unhashable type: 'list'
This error occurs when trying to use a list as a key in a dictionary or as an element in a set. Lists are mutable, meaning they can be changed after they are created, and therefore they are not hashable.
In order to fix this error, you can use a tuple instead of a list as a key in a dictionary or as an element in a set. Tuples are immutable, meaning they cannot be changed after they are created, and therefore they are hashable.
For example, instead of using a list as a key in a dictionary like this:
```
my_dict = {[1, 2]: 'value'}
```
You can use a tuple instead:
```
my_dict = {(1, 2): 'value'}
```
This will prevent the "unhashable type: 'list'" error from occurring.
TypeError: unhashable type: 'list'
这个错误通常发生在试图使用可变对象(比如列表)作为字典键或集合元素时。因为这些对象是可变的,它们的哈希值也可能发生变化,所以不能作为不可变对象使用。
以下是一个例子:
```python
my_list = [1, 2, 3]
my_dict = {my_list: 'value'}
```
在这个例子中,我们试图将一个列表作为字典的键,但是列表是可变的,所以不能作为键。如果我们运行这段代码,就会抛出“TypeError: unhashable type: 'list'”错误。
为了解决这个问题,可以将列表转换为元组,因为元组是不可变的,可以作为字典键或集合元素:
```python
my_list = [1, 2, 3]
my_dict = {tuple(my_list): 'value'}
```
这样就不会再出现“TypeError: unhashable type: 'list'”错误了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![dll](https://img-home.csdnimg.cn/images/20210720083646.png)