我在看《父與子的編程之旅》的時候,有段代碼是隨機畫100個矩形,矩形的大小,線條的粗細,顏色都是隨機的,代碼以下,python
import pygame,sys,random from pygame.color import THECOLORS pygame.init() screen = pygame.display.set_mode([640,480]) screen.fill([255,255,255]) for i in range(100): width = random.randint(0,250) height = random.randint(0,100) top = random.randint(0,400) left = random.randint(0,500) color_name = random.choice(THECOLORS.keys()) color = THECOLORS[color_name] line_width = random.randint(1,10) pygame.draw.rect(screen,color,[left,top,width,height],line_width) pygame.display.flip() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit()
結果,運行出錯,
TypeError: 'dict_keys' object does not support indexing編程
查了一下,發現這本書是基於python2.7來調試的,在python2中,key()方法返回的是一個列表,而在python3中,其返回的是一個dict_keys對象,因此咱們使用random_choice來隨機取一個列表元素的時候,在python3中,就不能直接使用,要使用list方法將dict_keys對象轉換成列表先,dom
這個問題,我開始沒有想到,在baidu上搜了半天,沒有相關的信息,最後仍是在stackoverflow上面找到的答案,python2.7
原文以下,ui
In Python 2.x, G.keys()
returns a list, but Python 3.x returns a dict_keys
object instead. The solution is to wrap G.keys()
with call to list()
, to convert it into the correct typespa