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

如何在Python脚本中为列表选项添加字母递增标记?

实现Python模板输出字母递增选项的解决方案

问题场景

原模板输出的选项格式为:

-[ ] selection one
-[ ] selection two
-[ ] selection three

需要修改为字母递增的形式:

a. selection one
b. selection two
c. selection three

原脚本中生成选项的代码片段如下:

def __str__(self):
    # show the correct order (noted by Sarah)
    self.options.sort(key=attrgetter('order'))
    # make sure it supports multiple correct selections
    correct_selection = ", ".join([
        str(selection)
        for selection
        in self.options
        if selection.correct
    ])

    # also, make sure it substitutes only the known values (see Tompei for ?)
    return _TEMPLATE.safe_substitute({
        'dilemma_ethos': self.text,
        'options': "\n".join([f'-[ ] {option}' for option in self.options]),
        'correct_selection': correct_selection,
    })

尝试通过bytes([ch[0] + 1])的方式实现字母递增时出现大量报错,需修改脚本达成需求。

修改步骤

  1. 首先导入string模块(如果脚本中还未导入):
import string
  1. 修改生成options的代码行,替换原有的列表推导式:
'options': "\n".join([f"{string.ascii_lowercase[i]}. {option}" for i, option in enumerate(self.options)]),

代码说明

  • string.ascii_lowercase返回完整的小写字母序列字符串'abcdefghijklmnopqrstuvwxyz',通过索引可以直接获取对应位置的字母
  • enumerate(self.options)遍历排序后的选项列表时,会同时返回每个选项的索引(从0开始)和选项内容,索引刚好对应字母序列的位置,实现a.到z.的递增
  • 如果你的选项数量可能超过26个,可以扩展逻辑生成多字母前缀(如aa.、ab.),但针对常规数量的选项,上述代码即可满足需求

修改后的完整__str__方法如下:

def __str__(self):
    # show the correct order (noted by Sarah)
    self.options.sort(key=attrgetter('order'))
    # make sure it supports multiple correct selections
    correct_selection = ", ".join([
        str(selection)
        for selection
        in self.options
        if selection.correct
    ])

    # also, make sure it substitutes only the known values (see Tompei for ?)
    return _TEMPLATE.safe_substitute({
        'dilemma_ethos': self.text,
        'options': "\n".join([f"{string.ascii_lowercase[i]}. {option}" for i, option in enumerate(self.options)]),
        'correct_selection': correct_selection,
    })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:04:50