lis中随机变量的选取

2024-05-13 01:12:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从列表中随机选取一个字典变量。我首先从列表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

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


Tags: import列表字典错误randomframeemoteprint
3条回答

在创建包含它的列表之前,必须定义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())]

在使用它之前,您需要定义

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

相关问题 更多 >