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

Python如何在动态列表的最后一个元素前插入指定元素

解法

要固定在列表最后一项的正前方插入"and",不需要提前记录列表长度,直接利用Python列表的索引规则计算插入位置即可:

  • list.insert(index, value)的作用是把value插入到索引为index的位置,原来在index及之后的元素会整体后移一位
  • 不管列表里有多少个元素,最后一个元素的索引永远是len(列表) - 1,把这个值传给insert的第一个参数,就能刚好把内容插在最后一个元素的前面
  • 加个简单的非空判断,避免空列表执行插入逻辑出现异常结果

完整修改代码

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

if len(listToPrint) > 0:
    listToPrint.insert(len(listToPrint) - 1, "and")

print(listToPrint)

运行效果参考

  • 依次输入apple、banana、cherry后按回车结束,输出为['apple', 'banana', 'and', 'cherry']
  • 只输入test就按回车结束,输出为['and', 'test']
  • 不输入任何内容直接按回车,输出为空列表[]

要是不需要在只有1个元素的列表里插入"and",把判断条件改成if len(listToPrint) >= 2就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:15:32