Python 在列表中选取随机变量

Python 在列表中选取随机变量,python,list,python-2.7,variables,random,Python,List,Python 2.7,Variables,Random,我试图从列表中选择一个随机字典变量。我首先从列表emotelist中选择一个随机变量 import random emotelist = [bored] emotechosen = random.choice(emotelist) emotename = emotechosen['emote'] emoteframe = emotechosen['frame'] bored = {'emote':'bored', 'frame':135} print emotename print emotef

我试图从列表中选择一个随机字典变量。我首先从列表
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:未定义名称“bored”


谢谢你的帮助。在创建变量列表之前,我应该在列表中定义变量。

在使用变量列表之前,需要定义变量:

import random
bored = {'emote':'bored', 'frame':135}
emotelist = [bored]
emotechosen = random.choice(emotelist)
emotename = emotechosen['emote']
emoteframe = emotechosen['frame']

在创建包含它的列表之前,必须定义

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

看起来您正在尝试打印随机字典值:

from random import choice

bored = {'emote':'bored', 'frame':135}
print bored[choice(bored.keys())]

在第2行中,您访问了无聊,但以前从未定义过无聊。您希望从这段代码中得到什么?您的代码在绑定到后面的行之前尝试使用名称
。请始终读取错误。它们是为人类设计的。但是OP定义了一个变量
perated
。代码的其余部分也是一团糟。执行此操作时,它会选择字符串,因此emotename和emoteframe无法获取字典值,因为字符串不是字典