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

Python新手求助:如何打印列表时排除最后一个元素?

问题解决:排除列表最后一个元素的正确切片写法
  • 你触发TypeError的核心原因是错误使用了逗号分隔索引listToPrint[0,-2]。Python列表的索引/切片语法中,逗号会被解析成元组,而列表不支持元组作为索引,因此抛出类型错误。
  • 要获取列表除最后一个元素外的所有内容,直接用Python切片语法list[:-1]即可。:-1表示从列表起始位置开始,取到倒数第一个元素的前一位(不包含最后一个元素)。

修正后的完整代码

# 先初始化列表,避免未定义的NameError
listToPrint = []

while True:
    newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
    if newWord == "":
        break
    else:
        listToPrint.append(newWord)

# 增加边界情况处理,让代码更健壮
if len(listToPrint) == 0:
    print("You didn't add any words.")
elif len(listToPrint) == 1:
    print(f"You want {listToPrint[0]}")
else:
    print(f'You want {listToPrint[:-1]} and {listToPrint[-1]}')

额外说明

原代码遗漏了listToPrint的初始化语句,运行时会触发NameError,上述代码已补充;同时增加了空列表和单元素列表的判断,避免列表长度不足时出现索引错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:06:41