在列表中挑选随机变量

时间:2015-02-22 14:21:28

标签: 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 emoteframe

但是我收到了错误

  

NameError:名称'无聊'未定义

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

3 个答案:

答案 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())]