在列表中的特定索引处插入元素并返回更新列表

ATO*_*TOA 73 python list insert python-2.7

我有这个:

>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]

>>> print a.insert(2, 3)
None

>>> print a
[1, 2, 3, 4]

>>> b = a.insert(3, 6)
>>> print b
None

>>> print a
[1, 2, 3, 6, 4]
Run Code Online (Sandbox Code Playgroud)

无论如何我可以获得更新的列表作为结果,而不是更新原始列表?

Rus*_*hal 70

l.insert(index, obj)实际上并没有返回任何内容,它只是更新列表.正如ATO所说,你可以做到b = a[:index] + [obj] + a[index:].但是,另一种方式是:

a = [1, 2, 4]
b = a[:]
b.insert(2, 3)
Run Code Online (Sandbox Code Playgroud)

  • 如果您无法容忍3行可读代码,请将其放入函数中并调用它. (53认同)
  • 该解决方案仍然会更新"a"列表.为了避免它,改变行的顺序:`b = a [:]; b.insert(2,3)` (10认同)

Moi*_*dri 36

最节能的方法

您还可以使用列表中的切片索引插入元素.例如:

>>> a = [1, 2, 4]
>>> insert_at = 2  # index at which you want to insert item

>>> b = a[:]   # created copy of list "a" as "b"
               # skip this step if you are ok with modifying original list

>>> b[insert_at:insert_at] = [3]  # insert "3" within "b"
>>> b
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

要在给定索引处将多个元素一起插入,您需要做的就是使用list要插入的多个元素.例如:

>>> a = [1, 2, 4]
>>> insert_at = 2   # index starting from which multiple elements will be inserted 

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]
Run Code Online (Sandbox Code Playgroud)

使用列表理解的替代方案 (但在性能方面非常慢):

作为替代方案,它可以使用来实现清单理解与enumerate过.(但请不要这样做.这只是为了说明):

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

所有解决方案的性能比较

以下是timeitPython 3.4.5的所有答案与1000个元素列表的比较:

  • 我真的很喜欢这个结果,因为它很容易扩展以解决问题,如果我想将值 `3, 3.5` 插入该列表(按顺序)-> `a[2:2] = [3,3.5]` . 非常整洁 (2认同)

ATO*_*TOA 31

最短的我得到: b = a[:2] + [3] + a[2:]

>>> 
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)