
本文讲解如何通过字典映射将用户输入的数字(如 "1")准确关联到对应字符串(如 "red"),并结合 colorama 实现带颜色提示的交互式选择,避免硬编码、提升可维护性。
本文讲解如何通过字典映射将用户输入的数字(如 "1")准确关联到对应字符串(如 "red"),并结合 colorama 实现带颜色提示的交互式选择,避免硬编码、提升可维护性。
在 Python 中,实现“用户输入数字 → 匹配指定字符串”这一需求,最清晰、健壮且可扩展的方式是使用字典(dict)作为映射表,而非依赖数组索引或多层 if-elif 判断。这不仅能确保语义明确(如 "1": "Red"),还能自然支持颜色前缀(如 Fore.RED)与名称的一一绑定。
以下是一个完整、可运行的教程示例,基于 colorama 库实现彩色菜单与输入校验:
✅ 推荐做法:用字典统一管理颜色名称与样式
import random
from colorama import init, Fore, Style
init() # 初始化 colorama(Windows 兼容必需)
# ✅ 核心映射:数字键(从1开始)→ 颜色名称 → 对应 Fore 样式
# 使用有序字典(Python 3.7+ dict 保持插入顺序)确保编号稳定
color_map = {
"Red": Fore.RED,
"Green": Fore.GREEN,
"Blue": Fore.BLUE,
"Yellow": Fore.YELLOW,
"Magenta": Fore.MAGENTA,
"Cyan": Fore.CYAN,
"Light Blue": Fore.LIGHTBLUE_EX
}
# ? 生成带颜色的编号菜单(自动适配新增颜色)
print(random.choice(list(color_map.values())) + "Type the number, not the color!" + Style.RESET_ALL + "\n")
for i, (name, style) in enumerate(color_map.items(), start=1):
print(f"{style}{i} = {name}{Style.RESET_ALL}")
# ? 随机展示一个颜色名称(带其对应颜色)
target_name = random.choice(list(color_map.keys()))
target_style = color_map[target_name]
print(f"\n{target_style}→ {target_name}{Style.RESET_ALL}")✅ 用户输入验证与匹配逻辑(关键补充)
上述代码仅完成显示,要真正“检查输入是否匹配”,需添加输入处理环节:
# ? 获取用户输入并验证
while True:
try:
user_input = input("\nEnter your choice (1–{}): ".format(len(color_map))).strip()
choice_num = int(user_input)
if 1 <= choice_num <= len(color_map):
# 将数字转为对应颜色名(按插入顺序)
selected_name = list(color_map.keys())[choice_num - 1]
print(f"{color_map[selected_name]}✓ You chose: {selected_name}{Style.RESET_ALL}")
# ✅ 可在此处判断是否匹配随机目标(如游戏逻辑)
if selected_name == target_name:
print(f"{Fore.GREEN}? Correct! The displayed color was '{target_name}'.{Style.RESET_ALL}")
else:
print(f"{Fore.RED}❌ Incorrect. Expected '{target_name}', got '{selected_name}'.{Style.RESET_ALL}")
break
else:
print(f"{Fore.YELLOW}⚠ Please enter a number between 1 and {len(color_map)}.{Style.RESET_ALL}")
except ValueError:
print(f"{Fore.YELLOW}⚠ Invalid input. Please enter a number.{Style.RESET_ALL}")⚠ 注意事项与最佳实践
- 避免数组索引陷阱:原问题中 words = ["Red", "Green", ...] 与 startcolor 列表顺序未严格对齐,易导致错位;字典映射彻底规避此风险。
- 扩展性强:新增颜色只需在 color_map 中追加一项,菜单、随机选择、验证逻辑全部自动生效。
- 类型安全:显式 int() 转换 + try/except 捕获非数字输入,防止 ValueError 崩溃。
- 用户体验:使用 Style.RESET_ALL 替代 Fore.RESET 更全面(重置所有样式,含背景、亮度等)。
- 兼容性:colorama.init() 在 Windows 上必不可少;Linux/macOS 可省略但建议保留。
通过该结构,你不仅实现了“输入数字 → 输出字符串”的核心功能,更构建了一个可维护、可测试、具备反馈机制的交互式颜色选择系统。
立即学习“Python免费学习笔记(深入)”;


















