在列表中选择随机变量

Picking random variable in list

我正在尝试从列表中随机选择一个字典变量。我首先从列表 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: name 'bored' is not defined

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

使用前需要先定义bored:

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

您必须先定义 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

您似乎在尝试打印随机字典值:

from random import choice

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