Python 在列表中修改 新增和刪除元素

2022-09-11 11:03:33 字數 3541 閱讀 6219

一、修改

**示例

motorcycles = ['

honda

', '

yamaha

', '

suzuki']

print(motorcycles)

motorcycles[

0] = '

ducati

'print(motorcycles)

執行結果['

honda

', '

yamaha

', '

suzuki']

['ducati

', '

yamaha

', '

suzuki

']

二、新增

**示例

motorcycles = ['

honda

', '

yamaha

', '

suzuki']

print(motorcycles)

'ducati')

print(motorcycles)

ducati

'新增到了列表末尾,而不影響列表中的其他所有元素:['

honda

', '

yamaha

', '

suzuki']

['honda

', '

yamaha

', '

suzuki

', '

ducati

'](二)使用insert()在列表任意位置插入元素(需要指定新元素的索引和值)

**示例

motorcycles = ['

honda

', '

yamaha

', '

suzuki']

motorcycles.insert(

0, '

ducati')

print(motorcycles)

執行結果['

ducati

', '

honda

', '

yamaha

', '

suzuki

']

三、刪除

(一)使用del語句刪除元素(知道要刪除的元素在列表中的位置)

**示例

motorcycles = ['

honda

', '

yamaha

', '

suzuki']

print(motorcycles)

del motorcycles[0]

print(motorcycles)

執行結果['

honda

', '

yamaha

', '

suzuki']

['yamaha

', '

suzuki

']

(二)使用方法pop()刪除元素(要將元素從列表中刪除,並接著使用它的值,可以使用pop()來刪除列表中任何位置的元素,只需在括號中指定要刪除的元素的索引即可。)

**示例①

motorcycles = ['

honda

', '

yamaha

', '

suzuki']

print(motorcycles)

popped_motorcycle =motorcycles.pop()

print(motorcycles)

print(popped_motorcycle)

執行結果①(.pop()刪除了列表中的末尾元素)['

honda

', '

yamaha

', '

suzuki']

['honda

', '

yamaha']

suzuki

**示例②

motorcycles = ['

honda

', '

yamaha

', '

suzuki']

first_owned = motorcycles.pop(0

) print(

'the first motorcycle i owned was a

' + first_owned.title() + '

.')

執行結果②

the first motorcycle i owned was a honda.

(三)根據值刪除元素(只知道要刪除的元素的值,不知道要從列表中刪除的值所處的位置。可使用方法remove(),可接著使用它的值)

**示例①

motorcycles = ['

honda

', '

yamaha

', '

suzuki

', '

ducati']

print(motorcycles)

motorcycles.remove(

'ducati')

print(motorcycles)

執行結果①['

honda

', '

yamaha

', '

suzuki

', '

ducati']

['honda

', '

yamaha

', '

suzuki

']

**示例②

motorcycles = ['

honda

', '

yamaha

', '

suzuki

', '

ducati']

print(motorcycles)

too_expensive = '

ducati

'motorcycles.remove(too_expensive)

print(motorcycles)

print(

"\na

" + too_expensive.title() + "

is too expensive for me.

")

執行結果②['

honda

', '

yamaha

', '

suzuki

', '

ducati']

['honda

', '

yamaha

', '

suzuki']

a ducati

is too expensive for me.

Python 列表中的修改 新增和刪除元素的實現

建立的列表大多數都將是動態的,這就意味著列表建立後,將隨著程式的執行刪減元素。修改列表元素 修改元素的的語法與訪問列表的語法類似。假設有乙個列表motorcycles,其中第乙個元素為 honda 修改第乙個元素的值 motorcycles honda yamaha suzuki print mot...

Python基礎 新增,修改和刪除列表元素

新增,修改和刪除元素也稱為更新列表。下面分別介紹如何實現列表元素的新增,修改和刪除。1.新增元素 其中listname是所要新增列表元素的列表名稱,obj表示新增到列表末尾的元素。verse 床前明月光 疑是地上霜 舉頭望明月 低頭思故鄉 此詩取自李白的 靜夜思 print verse 上面的 在d...

Python學習十五 新增 修改和刪除列表元素

其中,listname為要新增元素的列表名稱,obj為要新增到列表末尾的物件。verse 床前明月光 疑是地上霜 舉頭望明月 低頭思故鄉 len verse len verse print verse 我們在idle上執行一下 下面我們通過乙個具體的例項演示為列表新增元素的應用吧 場景模擬 有個老師...