在Python2.7中选择一个随机字典

2024-07-05 14:25:02 发布

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

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

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

有没有一种方法可以随机选择这三个字典中的一个在我的程序的其他地方使用?你知道吗

提前谢谢你的帮助。你知道吗


Tags: 方法name程序字典地方acspiderhp
3条回答

像这样使用random.choice

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))

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

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

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

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)

相关问题 更多 >