You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何根据随机选中的种族获取对应随机亚种?

问题分析与解决

你的代码有两处关键错误导致无输出:

  1. 判断条件逻辑错误:races_choice == subraces.keys()是拿单个种族字符串和字典的键集合(dict_keys对象)直接比较,永远不会相等。应该用in运算符判断选中的种族是否存在于subraces的键中。
  2. 字典取值语法错误:subraces.values[subraces.keys]完全不符合Python字典的取值规则,正确做法是用选中的种族作为键,直接从subraces中获取对应的子种族列表,即subraces[races_choice]。

修正后的代码

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:
    selected_subrace = random.choice(subraces[races_choice])
    print(f"选中种族:{races_choice},对应子种族:{selected_subrace}")
else:
    print(f"选中种族:{races_choice},无对应子种族")

简化优化方案

用字典的get方法可以省去显式的if判断逻辑:

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'],
}

subrace_list = subraces.get(races_choice)
print(random.choice(subrace_list) if subrace_list else f"{races_choice} 无对应子种族")

内容的提问来源于stack exchange,提问作者amryann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:24:56