插入特定索引的元素列表中,并返回更新列表(Insert an element at specific

2019-07-19 23:09发布

我有这个:

>>> 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]

反正我能得到更新的列表作为结果,而不是更新代替原来的名单?

Answer 1:

l.insert(index, obj)实际上并不返回任何东西,它只是更新列表。 作为ATO说,可以做b = a[:index] + [obj] + a[index:] 。 然而,另一种方式是:

a = [1, 2, 4]
b = a[:]
b.insert(2, 3)


Answer 2:

最短我得到: 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]


Answer 3:

大多数性能的高效方法

你也可以用切片的索引列表中插入元素。 例如:

>>> 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]

对于给定的索引处插入多个元素一起 ,所有你需要做的就是用一个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]

替代使用列表理解 (但在性能方面很慢):

作为替代方案,它可以使用列表中理解与实现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]

所有的解决方案的性能比较

这里的timeit所有1000个元素为Python 3.4.5的列表答案比较:

  • 矿回答使用切片插入-最快(每圈3.08微秒)

     mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]" 100000 loops, best of 3: 3.08 usec per loop 
  • ATOzTOA的接受的答案基于切片列表的合并-二(每圈6.71微秒)

     mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]" 100000 loops, best of 3: 6.71 usec per loop 
  • Rushy潘卡尔的答案 ,使用最多的选票list.insert(...) -三(每圈26.5微秒)

     python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)" 10000 loops, best of 3: 26.5 usec per loop 
  • 矿回答列表理解enumerate -四(很慢,每个回路168微秒)

     mquadri$ python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]" 10000 loops, best of 3: 168 usec per loop 


Answer 4:

使用Python列表insert()方法 。 用法:

句法

以下是insert()方法的语法 -

list.insert(index, obj)

参数

  • 指数 - 这是要插入的对象OBJ需要的指数。
  • OBJ - 这是要插入到指定的列表中的对象。

返回值

此方法不返回任何值,但它插入给定索引处的给定元素。

例:

a = [1,2,4,5]

a.insert(2,3)

print(a)

返回[1, 2, 3, 4, 5]



文章来源: Insert an element at specific index in a list and return updated list