我正在嘗試使用字典查找而不是使用繁瑣的多個 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 = 行中硬編碼與上面代碼中回傳的值完全相同的值時,我對為什么代碼成功運行感到困惑。我了解不可散列型別是什么,但是有人可以幫助我了解導致一行導致該錯誤的兩行中發生了什么變化。干杯。
uj5u.com熱心網友回復:
根據我在 PyGame 檔案(鏈接)中看到的您正在使用的代碼部分:
pygame.Surface.get_at
回傳顏色而不是元組。嘗試使用:
colour_under_mouse = tuple(pygame.Surface.get_at(screen, mouse_pos))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347784.html
上一篇:通過物件陣列中的鍵獲取元素
