首页 > 解决方案 > 如何通过使用python将现有值移动到下一个索引来在特定索引中的现有列表中插入值

问题描述

我有如下列表。

test = ['firstvalue', 'thirdvalue']

我想将一些值插入到列表中。索引 1 处的第二个值和索引 3 处的第四个值

所以输出列表如下所示

test = ['firstvalue', 'secondvalue', 'thirdvalue', 'fourthvalue']

我尝试了以下方式,但它对我不起作用

print test.insert(1, "secondvalue")

有没有其他方法可以做到这一点?

标签: pythonlistindexinginsert

解决方案


insert 函数不返回值,而是修改其上使用的数组。这是一个例子:

test = ['firstvalue', 'thirdvalue']
test.insert(1, "secondvalue")
print test

推荐阅读