首页 > 解决方案 > 为什么字典查找会导致“不可散列类型”错误,但使用直接值不会?

问题描述

我正在尝试使用字典查找而不是使用繁琐的多个 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 = 行中硬编码与上面代码中返回的值完全相同的值时,我对为什么代码运行成功感到困惑。我了解什么是不可散列的类型,但有人可以帮助我了解两行中发生了什么变化,导致一行导致该错误。干杯。

标签: pythondictionarypygametypeerror

解决方案


根据我在 PyGame (链接) 文档中看到的内容,您正在使用的代码部分:

pygame.Surface.get_at

返回颜色而不是元组。尝试使用:

colour_under_mouse = tuple(pygame.Surface.get_at(screen, mouse_pos))

推荐阅读