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
相关产品推荐
相关产品推荐

