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

13次阅读

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

本文介绍如何将模板中以 `- [ ]` 开头的选项列表,自动转换为带小写字母编号(如 `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 编号已足够——简洁、直观、符合阅读习惯。

立即学习Python免费学习笔记(深入)”;

text=ZqhQzanResources