Python选择题测验:如何为random.sample输出的字典项分配数字标签
为Python选择题测验的选项添加数字标签解决方案
嘿,我来帮你搞定这个给选择题选项加上数字编号的需求!
首先回顾下你的场景:你有一个存储水果与对应颜色的问答字典Qlib,还有一个Qshuffle函数用来随机生成测验题目,但目前输出的选项没有数字标签,我们只需要对生成选项的部分做一点小修改就能实现需求。
修改后的完整代码
import random # 你的问答字典 Qlib = dict() Qlib["Apple"]="green" Qlib["Orange"]="orange" Qlib["Banana"]="yellow" Qlib["Strawberry"]="red" def Qshuffle(self): choices = random.sample(list(Qlib),4) random_fruit = random.choice(choices) main_typed = "Which fruit is the following colour...??\n\n\n" print('{0} {1}\n\n'.format(main_typed, random_fruit.center(85))) # 核心修改:用enumerate生成带数字标签的选项 labeled_choices = [f"{index + 1}. {Qlib[fruit]}" for index, fruit in enumerate(choices)] print('Choices:\n' + "\n".join(labeled_choices))
关键修改说明
这里的核心技巧是使用Python的enumerate()函数——它能同时遍历choices列表中的元素和对应的索引值:
enumerate(choices)会返回一个个元组,格式是(索引值, 水果键)- 因为索引默认从0开始,我们用
index + 1得到从1开始的数字标签 - 用f-string把数字标签和对应的颜色值拼接成
"1. green"这样的格式,最后用"\n".join()把所有带标签的选项拼接成多行文本
示例输出
运行修改后的函数,你会得到类似这样的结果:
Which fruit is the following colour...??
StrawberryChoices:
- yellow
- green
- red
- orange
这样就完美实现了给选项添加数字标签的功能啦!
内容的提问来源于stack exchange,提问作者Crash Bandicoot
相关产品推荐
相关产品推荐

