Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python 2.7中选择一个随机字典_Python_Python 2.7_Dictionary - Fatal编程技术网

在Python 2.7中选择一个随机字典

在Python 2.7中选择一个随机字典,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,我试图找出如何在Python2.7中选择一个随机字典。如果我有三本这样的词典: monster1 = {'name' : 'kobold', 'AC' : 5, 'HP' : 8} monster2 = {'name' : 'spider', 'AC' : 6, 'HP' : 10} monster3 = {'name' : 'ogre', 'AC' : 6, 'HP' : 12} 有没有办法从这三本字典中随机选择一本在我的程序中的其他地方使用 提前感谢您的帮助。您可以将它们放入列表中,然后使

我试图找出如何在Python2.7中选择一个随机字典。如果我有三本这样的词典:

monster1 = {'name' : 'kobold', 'AC' : 5, 'HP' : 8}
monster2 = {'name' : 'spider', 'AC' : 6, 'HP' : 10}
monster3 = {'name' : 'ogre', 'AC' : 6, 'HP' : 12}
有没有办法从这三本字典中随机选择一本在我的程序中的其他地方使用


提前感谢您的帮助。

您可以将它们放入列表中,然后使用
random.choice()
随机获取其中一个。例如:

import random
random_dict = random.choice([monster1, monster2, monster3])

使用
random。像这样选择

import random

monster1 = {'name' : 'kobold', 'AC' : 5, 'HP' : 8}
monster2 = {'name' : 'spider', 'AC' : 6, 'HP' : 10}
monster3 = {'name' : 'ogre', 'AC' : 6, 'HP' : 12}

choices = [monster1, monster2, monster3]

print(random.choice(choices))

+1与kichik的回答一致

如果您确实设置为不使用列表,eval命令也将为您提供所需的结果

from random import randint

eval('monster'+str(randint(1,3)))
{'AC': 6, 'HP': 12, 'name': 'ogre'}
eval('monster'+str(randint(1,3)))
{'AC': 5, 'HP': 8, 'name': 'kobold'}

您可以将字典放入一个数组中,然后选择一个随机索引

from random import choice
monster1 = {'name' : 'kobold', 'AC' : 5, 'HP' : 8}
monster2 = {'name' : 'spider', 'AC' : 6, 'HP' : 10}
monster3 = {'name' : 'ogre', 'AC' : 6, 'HP' : 12}
monsters = [monster1, monster2, monster3]
randmonster = choice(monsters)

不要把这些单词分配给他们自己的名字,而是把它们列出来。因此,您将有一个包含3个dict的列表,您可以很容易地从中随机选择,因为只有3个字典可供选择。虽然没有太多的随机性,但您可以生成一个介于1和3之间的值,然后编写一个if-else语句,根据该数字选择一个字典。感谢所有的答案。我真的很感谢大家花时间回答这个问题。与其使用
eval
,不如使用
globals()['monster'+number]