[英]Is it possible to insert a value into the last index of a list in python?
因此,我最近注意到,無法使用“插入”方法將值插入列表的最后一個索引,並且想知道是否需要采取一些額外的步驟,或者是否根本不可能。 如果不可能使用“插入”,如果有人知道一種解決方法,我將不勝感激。 我知道在沒有“插入”方法的情況下如何實現它,但是如果有更好的方法,我希望這樣做。 我知道您可以簡單地獲取列表的長度並將其用作索引。
提前致謝。
你不能使用這樣的東西嗎?
l = [1,2,3,4]
l.insert(len(l),5)
print l
[1,2,3,4,5]
使用append方法。 像這樣
a.append(x)
這x插入到列表中的最后一個索引a
即列表的末尾a
。 例如:
a = ["apples", "bananas", "oranges"]
a.append("lemons")
print (a)
這將打印:
["apples", "bananas", "oranges", "lemons"]
您也可以使用insert這樣做:
a.insert(len(a), x)
但是,上面使用的insert
方法效率很低,也不易讀。 因此,我建議您使用append
方法。
有關更多信息,請訪問https://docs.python.org/3.6/tutorial/datastructures.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.