Python 错误 TypeError: Unhashable Type: List

文章目录

    • Python 中的 TypeError: unhashable type: ‘list’
    • Python 中的哈希函数
    • 修复 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”作为键,使用它很好,因为字符串是可变的。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年12月26日
下一篇 2023年12月26日

相关推荐