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

如何在Python中为指定列表项前置添加‘X ’标识?

问题

需求是:程序展示待办列表,询问用户已完成的列表项,当用户输入列表中的某一项后,在该项前插入“X ”。例如初始列表为["homework", "chores"],用户输入“homework”后,列表变为["X homework", "chores"]。现有代码片段如下:

run = True
while run:
    input000 = input("Which items do you wish to record as done?")
# Something the adds X to the front of the chosen list item (from the input)
解决方案

首先需要初始化待办列表,在循环中处理用户输入、匹配列表项并完成标记,同时补充退出逻辑让程序更易用。完整实现代码如下:

# 初始化待办列表
todo_list = ["homework", "chores"]

run = True
while run:
    # 展示当前待办状态
    print("当前待办:", todo_list)
    input000 = input("Which items do you wish to record as done? (输入quit退出)")
    
    # 退出程序的逻辑
    if input000.lower() == "quit":
        run = False
        continue
    
    # 遍历列表查找目标项并标记
    for idx, item in enumerate(todo_list):
        # 避免重复标记已完成项
        if item == input000:
            todo_list[idx] = f"X {input000}"
            print(f"已标记 '{input000}' 为完成")
            break
    else:
        # 输入项不在列表中时提示
        print("输入的项不在待办列表里,请重新输入")

核心逻辑说明

  • 每次循环先打印当前列表,让用户明确可选的待办项
  • 加入quit退出指令,避免程序无限循环无法终止
  • 使用enumerate同时获取列表索引和元素,找到目标项后直接修改对应位置的元素,添加"X "前缀
  • 增加输入校验,当用户输入不存在的项时给出提示,提升交互体验

内容的提问来源于stack exchange,提问作者Monkey D Luffy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:15:33