python - 为什么字典查找会导致“不可散列类型”错误,但使用直接值不会?
问题描述
我正在尝试使用字典查找而不是使用繁琐的多个 if 语句来改进一些代码。但是,当我尝试使用派生的变量运行代码时,代码会返回“TypeError:unhashable type”,但如果我运行相同的代码但使用直接值而不是派生值,则代码会运行。
这是失败的代码:
def colour_check_under_mouse():
global d_colours
mouse_pos = pygame.mouse.get_pos()
if pygame.mouse.get_pressed()[0]:
colour_under_mouse = pygame.Surface.get_at(screen, mouse_pos)
print(colour_under_mouse)
colour_selected = d_colours[colour_under_mouse]
# colour_selected = d_colours[255, 0, 0, 255]
print(colour_selected)
在将注释掉的行替换为带有硬编码值的行之后,这是运行的代码:
def colour_check_under_mouse():
global d_colours
mouse_pos = pygame.mouse.get_pos()
if pygame.mouse.get_pressed()[0]:
colour_under_mouse = pygame.Surface.get_at(screen, mouse_pos)
print(colour_under_mouse)
# colour_selected = d_colours[colour_under_mouse]
colour_selected = d_colours[255, 0, 0, 255]
print(colour_selected)
使用的字典是:
d_colours = {(255, 0, 0, 255): 'Red', (0, 255, 0, 255): 'Green', (0, 0, 255, 255): 'Blue', (255, 255, 0, 255): 'Yellow'}
当我在 colour_selected = 行中硬编码与上面代码中返回的值完全相同的值时,我对为什么代码运行成功感到困惑。我了解什么是不可散列的类型,但有人可以帮助我了解两行中发生了什么变化,导致一行导致该错误。干杯。
解决方案
根据我在 PyGame (链接) 文档中看到的内容,您正在使用的代码部分:
pygame.Surface.get_at
返回颜色而不是元组。尝试使用:
colour_under_mouse = tuple(pygame.Surface.get_at(screen, mouse_pos))
推荐阅读
- c# - 如果收益返回不产生结果,则返回/继续代码?
- symfony - 错误类“用户”不存在;请输入现有的完整班级名称。(交响乐)
- python - 使用“try”和“exept”处理 In-stagram 机器人中的错误
- javascript - 加载另一个 html 页面并滚动到内页 div
- c - 致命错误:stdarg.h:编译wine时没有这样的文件或目录,但文件存在
- jestjs - 开玩笑 - 我如何导出测试文档以便与同事共享测试?
- node.js - MongoDB TTL - 何时何地?
- android - Android Studio 4 将 kotlin 类代码替换为一些垃圾 XML
- azure - Nginix 超时的最大值是多少
- php - 尝试在 php 字节码中阻止范围信息