Login
主页 > 教程文章 > 后端开发

如何在 Python 中将列表项按字母顺序编号(a.、b.、c. …)

花韻仙語 2025-12-31 00:00:00 人看过

本文介绍如何将模板中以 `- [ ]` 开头的选项列表,自动转换为带小写字母编号(如 `a. selection one`)的格式,适用于生成题干、问卷或文档类输出。

在 Python 中实现字母序号(a, b, c, …)编号,本质是将索引 0, 1, 2, ... 映射为 ASCII 字符 'a', 'b', 'c', ...,可借助 chr(ord('a') + i) 完成。关键在于:安全提取原始文本内容(去除 -[ ] 前缀),并按行枚举、逐行重写

以下是你原 __str__ 方法中 options 字段的优化方案:

from operator import attrgetter

def __str__(self):
    # 按 order 排序选项(保持逻辑不变)
    self.options.sort(key=attrgetter('order'))

    # 构建带字母编号的选项列表:a. xxx, b. xxx, ...
    numbered_options = []
    for i, option in enumerate(self.options):
        # 使用 chr(97 + i) → 'a', 'b', 'c', ...;97 是 'a' 的 ASCII 码
        if i >= 26:
            raise ValueError("Too many options: alphabetical numbering supports only a–z (26 items)")
        letter = chr(97 + i)  # 97 → 'a', 98 → 'b', etc.
        numbered_options.append(f"{letter}. {option}")

    correct_selection = ", ".join(
        str(selection) for selection in self.options if selection.correct
    )

    return _TEMPLATE.safe_substitute({
        'dilemma_ethos': self.text,
        'options': "\n".join(numbered_options),  # 替换为字母编号版本
        'correct_selection': correct_selection,
    })

注意事项:

  • chr(97 + i) 仅支持最多 26 个选项(a–z)。若需更多(如 aa, ab… 或 1, 2, 3),应改用 string.ascii_lowercase 循环或第三方库(如 more-itertools.chunked 配合自定义编号器)。
  • 原始模板中 -[ ] 占 5 个字符(含空格),但本方案直接使用 option 对象的 __str__() 输出,避免硬编码切片(如 line[5:]),更健壮、语义清晰。
  • 若 option 对象的 __str__() 返回值含意外换行或缩进,建议统一用 str(option).strip() 防御处理。

? 进阶提示(支持 >26 项):
如需扩展至 27+ 项(如 aa, ab, ac…),可引入如下通用函数:

def alphabetize(items):
    from string import ascii_lowercase
    result = []
    for i, item in enumerate(items):
        q, r = divmod(i, 26)
        prefix = ascii_lowercase[r]
        if q > 0:
            prefix = ascii_lowercase[q - 1] + prefix  # aa, ab, ..., az, ba...
        result.append(f"{prefix}. {str(item).strip()}")
    return result

但对绝大多数教育/测试场景,a–z 编号已足够——简洁、直观、符合阅读习惯。

本站文章内容,部分来源于网络搜集发布,如有侵权,请联系我们修改或者删除处理。

课程推荐

热门文章

Copyright © 2016-2024 杭州鸣程科技有限公司 版权所有
浙ICP备2024057137号-1 浙公网安备33018502002374号 
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报电话:400-117-8398,QQ:
800881121,邮箱:mc93go@foxmail.com