本文介紹了如何使用 list.insert 將 Python 中的元素添加到列表末尾?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
有一個列表,例如,
a=[1,2,3,4]
我可以使用
a.append(some_value)
在列表末尾添加元素,并且
to add element at the end of list, and
a.insert(exact_position, some_value)
在列表中的任何其他位置插入元素但不是在末尾??strong>作為
to insert element on any other position in list but not at the end as
a.insert(-1, 5)
將返回 [1,2,3,5,4].那么如何使用 list.insert(position, value) 將元素添加到列表末尾?
will return [1,2,3,5,4]. So how to add an element to the end of list using list.insert(position, value)?
推薦答案
在這種情況下,您必須使用 len
將新的序數位置傳遞給 insert
:
You'll have to pass the new ordinal position to insert
using len
in this case:
In [62]:
a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]
這篇關于如何使用 list.insert 將 Python 中的元素添加到列表末尾?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!