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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14895599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:47:08  来源:igfitidea点击:

Insert an element at specific index in a list and return updated list

pythonpython-2.7listinsert

提问by ATOzTOA

I have this:

我有这个:

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

Is there anyway I can get the updated list as result, instead of updating the original list in place?

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

采纳答案by ATOzTOA

Shortest I got: b = a[:2] + [3] + a[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]

回答by Rushy Panchal

l.insert(index, obj)doesn't actually return anything, it just updates the list. As ATO said, you can do b = a[:index] + [obj] + a[index:]. However, another way is:

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

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

回答by Moinuddin Quadri

Most Performance Efficient approach

最高效的方法

You may also insert the element using the slice indexingin the list. For example:

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

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

For inserting multiple elements together at a given index, all you need to do is to use a listof multiple elements that you want to insert. For example:

在给定的 index 处一起插入多个元素,您需要做的就是使用list要插入的多个元素的a 。例如:

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


Alternative using List Comprehension(but very slow in terms of performance):

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

As an alternative, it can be achieved using list comprehensionwith enumeratetoo. (But please don't do it this way. It is just for illustration):

作为替代方案,它可以使用来实现清单理解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]


Performance Comparison of all solutions

所有解决方案的性能比较

Here's the timeitcomparison of all the answers with list of 1000 elements for Python 3.4.5:

timeit是所有答案与 Python 3.4.5 的 1000 个元素列表的比较:

  • Mine answerusing sliced insertion - Fastest (3.08 usec per loop)

    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's accepted answerbased on merge of sliced lists - Second (6.71 usec per loop)

    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 Panchal's answerwith most votes using list.insert(...)- Third (26.5 usec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    10000 loops, best of 3: 26.5 usec per loop
    
  • Mine answerwith List Comprehensionand enumerate- Fourth (very slow with 168 usec per loop)

    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
    
  • 我的答案使用切片插入 - 最快(每个循环 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 usec)

    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 Panchal 的回答最多使用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
    
  • 我的答案List Comprehensionenumerate- 第四(非常慢,每个循环 168 usec)

    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
    

回答by Arjun Sanchala

Use the Python list insert() Method. Usage:

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

Syntax

Following is the syntax for insert() method ?

list.insert(index, obj)

Parameters

  • index ? This is the Index where the object obj need to be inserted.
  • obj ? This is the Object to be inserted into the given list.

Return Value

This method does not return any value but it inserts the given element at the given index.

句法

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

list.insert(index, obj)

参数

  • 指数 ?这是需要插入对象 obj 的索引。
  • 对象?这是要插入给定列表的对象。

返回值

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

Example:

例子:

a = [1,2,4,5]

a.insert(2,3)

print(a)

Returns [1, 2, 3, 4, 5]

退货 [1, 2, 3, 4, 5]