python-3.x - 在随机选择键后从字典中随机选择一个值

标签 python-3.x

我正在尝试用 python 制作一个命运之轮类型的游戏。我有从字典中随机选择一个键的代码,但我不确定如何从该特定键中选择一个随机值。

categories = {'Sayings': ['Actions speak louder than words', 'A bird in the hand is worth two in the bush',
                      'All good things come to an end', 'Among the blind the one eyed man is king',
                      'Fortune favors the bold', 'Ignorance is bliss'],'70s Soul Musicians': ['James Brown', 'Sly Stone', 'Aretha Franklin', 'Earth Wind & Fire', 'Stevie Wonder',
                        'Chaka Khan']}

程序选择一个随机键/类别让玩家猜测。

randCategory = str(random.choice(list(categories)))
print(randCategory)

最佳答案

试试这个

import random

categories = {
    'Sayings': [
        'Actions speak louder than words',
        'A bird in the hand is worth two in the bush',
        'All good things come to an end',
        'Among the blind the one eyed man is king',
        'Fortune favors the bold',
        'Ignorance is bliss'
    ],
    '70s Soul Musicians': [
        'James Brown',
        'Sly Stone',
        'Aretha Franklin',
        'Earth Wind & Fire',
        'Stevie Wonder','Chaka Khan'
    ]
}

randCategory = str(random.choice(list(categories)))
randValue = str(random.choice(list(categories[randCategory])))

print(randCategory)
print(randValue)

关于python-3.x - 在随机选择键后从字典中随机选择一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57748633/

相关文章:

python - 如何在Turtle中制作笑脸?

python - 悬停在Kivy ActionBar ActionButton上

python - 为什么我的 python 打印比 Go 的 fmt.Print 和 os.Stdout.Write 运行得更快

python - 如何在Python列表中查找特定字符串,如果找到则打印位置,否则打印0

python - 在 pygmo 中使用队列进行函数评估

python - Python 3 中的嵌套 map

python - 从请求导入 PandaRequest ImportError : No module named 'request'

python - _tkinter.TclError : encountered an unsupported criticial chunk type "exIf"

python - 操作系统错误 : exception: access violation reading with Cyphon basic example

python - 使用 django channel 从 python 3.6 升级到 python 3.7 时出现 SynchronousOnlyOperation 错误