Python 列表中的修改、新增和刪除元素的實現
本文介紹的是列表中的修改、新增和刪除元素。第一次寫部落格,如果本文有什麼錯誤,還請大家評論指正。謝謝!
建立的列表大多數都將是動態的,這就意味著列表建立後,將隨著程式的執行刪減元素。
修改列表元素
修改元素的的語法與訪問列表的語法類似。
假設有一個列表motorcycles,其中第一個元素為'honda',修改第一個元素的值
motorcycles = ['honda','yamaha','suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) ['honda','suzuki'] ['ducati','suzuki']
列表中第一個元素的值變成了'ducati'
新增列表元素
在列表末尾新增元素
motorcycles = ['honda','suzuki'] motorcycles.append('ducati') print(motorcycles) ['honda','suzuki','ducati']
方法append()是將元素'ducati'新增到了列表的末尾,那如果我們想將元素插入到列表元素的中間怎麼辦?方法insert()解決這個問題。
motorcycles = ['honda','suzuki'] motorcycles.insert(1,'ducati') print(motorcycles) ['honda','ducati','suzuki']
元素'ducati'插入在了列表中第二個位置上,這是因為在python程式中,是從0開始計數的,所以'ducati'放在了元素'honda'的後面。
刪除列表元素
使用del 語句刪除元素
motorcycles = ['honda','suzuki'] del motorcycles[1] print(motorcycles) ['honda','suzuki']
刪除第二個元素,同理在python程式中,是從0開始計數的,即刪除的是'yamaha'
使用 pop()刪除元素
pop() 可刪除列表中末尾的元素,並讓你能夠接著使用它。術語彈出(pop)源自這樣的類比:列表就像是一個棧,而刪除的列表末尾相當於彈出棧頂元素。
motorcycles = ['honda','suzuki'] last_owned = motorcycles.pop() print(last_owned) print(motorcycles) suzuki ['honda','yamaha']
實際上,我們也可以使用pop()刪除任何位置的元素,只需要在括號中指定要刪除的元素索引即可。
motorcycles = ['honda','suzuki'] last_owned = motorcycles.pop(0) print(last_owned) honda
使用remove 語句刪除元素
有的時候,我們不知道從列表中刪除的位置。如果你只知道要刪除元素的值,則可以使用remove()。
例如:我們要從motorcycles列表中刪除'ducati'
motorcycles = ['honda','ducati'] motorcycles.remove('ducati') print(motorcycles) ['honda','suzuki']
注意:remove()只能刪除第一個指定的值。如果要刪除的值可能在列表中出現多次,就需要使用迴圈判斷是否刪除了所有這樣的值。
到此這篇關於Python 列表中的修改、新增和刪除元素的實現的文章就介紹到這了,更多相關Python 修改新增刪除元素內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!