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

Python实现列表项带索引打印及去除末尾逗号的问题

解决方案

以下是修正后的完整代码,同时解决需求并匹配预期输出:

things = ['humans', 'fish', 'plants', 'planets', 'stars']

print('These are types of things we learnt so far:')
# 生成1开始的带索引条目
labeled_items = [f"{idx+1}) {item}" for idx, item in enumerate(things)]
# 用逗号连接所有条目,避免末尾多余逗号
print(', '.join(labeled_items))
print()

# 按预期格式提示输入
selected_num = int(input('Now please enter a number which you want to print:\n'))
# 转换为列表的0-based索引
print(f'You have chosen {selected_num} which is {things[selected_num-1]}.')

问题解决说明

  • 带索引格式打印:用enumerate()遍历列表获取元素的0-based索引,通过idx+1转换为用户习惯的1开始序号,再用列表推导式生成序号) 元素格式的字符串。
  • 消除末尾多余逗号:不再用循环逐个打印并设置end=', ',而是将所有带索引的字符串用', '.join()方法拼接,该方法只会在元素之间添加分隔符,自然避免末尾出现多余逗号。
  • 额外修正:原代码直接用输入数字作为列表索引会报错(用户输入的是1-based序号,Python列表是0-based索引),因此添加selected_num-1的转换,匹配预期输出逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 00:22:02