如何使用list.insert将Python中的元素添加到列表的末尾?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30212447/
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-19 08:04:00  来源:igfitidea点击:

How to add element in Python to the end of list using list.insert?

pythonlistinsert

提问by Andersson

There is a list, for example,

有一个列表,例如,

a=[1,2,3,4]

I can use

我可以用

a.append(some_value)

to add element at the end of list, and

在列表末尾添加元素,以及

a.insert(exact_position, some_value)

to insert element on any other position in list but not at the endas

插入元素在列表中的任何其他位置,但不能在最后

a.insert(-1, 5)

will return [1,2,3,5,4]. So how to add an element to the end of list using list.insert(position, value)?

将返回 [1,2,3, 5,4]。那么如何使用list.insert(position, value)将元素添加到列表的末尾?

采纳答案by EdChum

You'll have to pass the new ordinal position to insertusing lenin this case:

在这种情况下,您必须将新的序数位置传递给insertusing len

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

回答by Jonathan L

list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

list.insert 与任何索引 >= len(of_the_list) 将值放在列表的末尾。它的行为类似于追加

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

Time complexity, append O(1), insert O(n)

时间复杂度,追加 O(1),插入 O(n)