Python 错误 TypeError: Unhashable Type: List
本文将讨论 TypeError: unhashable type: 'list' 以及如何在 Python 中修复它。
Python 中的 TypeError: unhashable type: 'list'
当您将不可散列的对象(如列表)作为键传递给 Python 字典或查找函数的散列值时,会发生此错误。
字典是 Python 中的一种数据结构,以键值对的形式工作,每个键都有一个对应的值,要访问值的值,您将需要像数组索引这样的键。
字典的语法:
dic ={ "key": "Values"}
可哈希对象是那些值不随时间变化但保持不变的对象,元组和字符串是可哈希对象的类型。
代码:
# creating a dictionary
dic = {
# list as a key --> Error because lists are immutable
["a","b"] : [1,2]
}
print(dic)
输出:
TypeError: unhashable type: 'list'
我们使用列表 ["a","b"]
作为键,但编译器抛出了一个 **TypeError: unhashable type: 'list'**。
让我们手动查找列表的哈希值。
代码:
lst = ["a","b"]
hash_value = hash(lst)
print(hash_value)
输出:
TypeError: unhashable type: 'list'
hash()
函数用于查找给定对象的哈希值,但该对象必须是不可变的,如字符串、元组等。
Python 中的哈希函数
hash()
函数是一种加密技术,它加密不可变对象并为其分配一个唯一值,称为对象的哈希值。 无论数据大小如何,它都提供相同大小的唯一值。
代码:
string_val = "String Value"
tuple_val = (1,2,3,4,5)
msg= """Hey there!
Welcome to jiyik.com"""
print("Hash of a string object\t\t", hash(string_val))
print("Hash of a tuple object\t\t", hash(tuple_val))
print("Hash of a string message\t", hash(tuple_val))
输出:
Hash of a string object -74188595
Hash of a tuple object -1883319094
Hash of a string message -1883319094
散列值大小相同,并且对于每个值都是唯一的。
修复 Python 中的 TypeError: unhashable type: 'list'
要修复 Python 中的 TypeError,您必须使用不可变对象作为字典的键和 hash()
函数的参数。 请注意,在上面的代码中,hash() 函数与元组和字符串等可变对象完美配合。
让我们看看如何修复字典中的 TypeError: unhashable type: 'list' 。
代码:
# creating a dictionary
dic = {
# string as key
"a" : [1,2]
}
print(dic)
输出:
{'a': [1, 2]}
这次我们提供一个字符串“a”作为键,使用它很好,因为字符串是可变的。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串