我试图从列表中选择一个随机字典变量。我首先从列表emotelist
中选择一个随机变量。
import random
emotelist = [bored]
emotechosen = random.choice(emotelist)
emotename = emotechosen['emote']
emoteframe = emotechosen['frame']
bored = {'emote':'bored', 'frame':135}
print emotename
print emoteframe
但是我收到了错误
NameError:名称'无聊'未定义
感谢您的帮助。在创建变量列表之前,我应该在列表中定义我的变量。
答案 0 :(得分:4)
您必须先定义bored
,然后创建一个包含它的列表:
import random
# move bored definition here:
bored = {'emote':'bored', 'frame':135}
# now use it in a list construction
emotelist = [bored]
emotechosen = random.choice(emotelist)
emotename = emotechosen['emote']
emoteframe = emotechosen['frame']
print emotename
print emoteframe
答案 1 :(得分:0)
在使用之前,您需要定义无聊:
import random
bored = {'emote':'bored', 'frame':135}
emotelist = [bored]
emotechosen = random.choice(emotelist)
emotename = emotechosen['emote']
emoteframe = emotechosen['frame']
答案 2 :(得分:0)
看起来您正在尝试打印随机字典值:
from random import choice
bored = {'emote':'bored', 'frame':135}
print bored[choice(bored.keys())]