[英]Python: How to get a value from randomly selected key in a dictionary
我在这里要做的是从列表中随机选择
races = ['Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf', 'Halfling', 'Half-Orc', 'Human', 'Tiefling']
races_choice = random.choice(races)
然后使用列表中的随机选择来查看单独字典中的键
subraces = {
'Dwarf': ['Hill Dwarf', 'Mountain Dwarf'],
'Elf': ['High Elf', 'Wood Elf', 'Dark Elf'],
'Halfling': ['Lightfoot', 'Stout'],
'Gnome': ['Forest Gnome', 'Rock Gnome'],
}
如果该键与随机选择匹配,则从该键中打印一个随机值。
我已经尝试了一些事情,但我目前正在做的是:
if races_choice == subraces.keys():
print(random.choice(subraces.values[subraces.keys]))
但这没有任何回报。 我对如何做到这一点有点不知所措。
谢谢你。
您可以简单地在字典上使用.get
。
DEFAULT_VALUE = "default value"
subraces = {
'Dwarf': ['Hill Dwarf', 'Mountain Dwarf'],
'Elf': ['High Elf', 'Wood Elf', 'Dark Elf'],
'Halfling': ['Lightfoot', 'Stout'],
'Gnome': ['Forest Gnome', 'Rock Gnome'],
}
races = ['Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf',
'Halfling',
'Half-Orc', 'Human', 'Tiefling']
races_choice = random.choice(races)
subrace_options = subraces.get(races_choice, DEFAULT_VALUE)
if subrace_options != DEFAULT_VALUE:
index = random.randint(0, (len(subrace_options) - 1))
print(subrace_options[index])
else:
print("No subrace for specified race")
这将产生来自给定种族的子种族的名称,例如对于Dwarf
,output 将是列表中的随机条目,即Hill Dwarf
。
.get
中的字符串值是默认值,如果在子种族的 map 中找不到密钥(随机选择),则将分配该值。
似乎您可以根据键简单地设置一个随机 int 等效于项目的长度
import random
races = ['Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf', 'Halfling', 'Half-Orc', 'Human', 'Tiefling']
races_choice = random.choice(races)
subraces = {
'Dwarf': ['Hill Dwarf', 'Mountain Dwarf'],
'Elf': ['High Elf', 'Wood Elf', 'Dark Elf'],
'Halfling': ['Lightfoot', 'Stout'],
'Gnome': ['Forest Gnome', 'Rock Gnome']}
if races_choice in subraces:
print(subraces[races_choice][random.randint(0, len(subraces[races_choice]) - 1)]) # -1 since lists starts from 0, not 1
else:
print('"' + races_choice + '"', 'has no subraces')
你也可以尝试这样的事情:
from random import choice
print(choice(subraces.get(choice(races),[0])) or 'no matches')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.