在学习《与孩子一起学编程python》课程16.3中,遇到的“"dict_keys"object is no callable”的问题。
源码如下:
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_name=random.choice(list(THECOLORS.keys()))
color = THECOLORS[color_name]
line_width=random.randint(1,3)
pygame.draw.rect(screen,color,[left,top,width,height],line_width)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
python2.x和3.X对于dict的定义和使用发生了一些改变,一些函数在提出字典内容后仍然为字典,需要list函数将其转换为列表。
>>> color_name=random.choice(THECOLORS.keys())
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
color_name=random.choice(THECOLORS.keys())
File "C:\Program Files\Python36\lib\random.py", line 258, in choice
return seq[i]
TypeError: 'dict_keys' object does not support indexing
>>> type(THECOLORS.keys())
<class 'dict_keys'>
>>> type(list(THECOLORS.keys()))
<class 'list'>
>>>
我们在Python3. 6.3 document中可以看到 random.choice()函数操作的是一个sequence值,而不是dict。
random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.