【问题标题】:How to insert value in existing list in a specific index by moving the existing value to next index using python如何通过使用python将现有值移动到下一个索引来在特定索引中的现有列表中插入值
【发布时间】:2019-05-04 20:06:32
【问题描述】:

我有如下列表。

test = ['firstvalue', 'thirdvalue']

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

所以输出列表如下所示

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

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

print test.insert(1, "secondvalue")

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

【问题讨论】:

  • @timgeb - 我正在编辑我的问题
  • insert 不返回列表,在test.insert 之后尝试print(test)
  • “它对我不起作用”,但实际发生了什么?您需要解释实际结果与预期结果才能有所帮助。
  • @VPfB - 不工作
  • @sushil 你知道,你真的可以通过重复“不工作”作为问题的解释让人们发疯。

标签: python list indexing insert


【解决方案1】:

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

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

【讨论】:

  • 我们可以在单个插入中添加多个值
  • @sushil 不,你不能。
  • 感谢回复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 2017-11-11
相关资源
最近更新 更多