0
点赞
收藏
分享

微信扫一扫

修改、添加和删除列表元素(python)

大南瓜鸭 2022-03-12 阅读 99

修改、添加和删除列表元素(python)



文章目录


motorcycles[0] = 'ducati', .append(), .insert(), del, .pop()删除末尾元素, .pop(3), .remove(), .remove('honda')

修改列表元素

根据索引直接对列表中的元素赋值:

>>> motorcycles = ['honda', 'yamaha', 'suzuki']
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki']
>>> motorcycles[0] = 'ducati'
>>> print(motorcycles)
['ducati', 'yamaha', 'suzuki']

在列表中添加元素

列表末尾添加元素

.append()

>>> motorcycles = ['honda', 'yamaha', 'suzuki']
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki']
>>> motorcycles.append('ducati')
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']

列表中插入元素

.insert()
.insert()操作将列表中既有的每个元素都右移一个位置:

>>> motorcycles = ['honda', 'yamaha', 'suzuki']
>>> motorcycles.insert(0, 'ducati']
>>> print(motorcycles)
['ducati', 'honda', 'yamaha', 'suzuki']

从列表中删除元素

使用del语句删除元素

如果知道要删除的元素在列表中的位置,可使用del语句。

>>> motorcycles = ['honda', 'yamaha', 'suzuki']
>>>> print(motorcycles)
['honda', 'yamaha', 'suzuki']
>>> del motorcycles[0]
>>> print(motorcycles)
['yamaha', 'suzuki']

使用del语句将值从列表中删除后,你就无法再访问它了

使用方法pop()删除元素

有时候,你将元素从列表中删除,并接着使用它的值,此时使用.pop()
方法pop()删除列表末尾的元素,并让你能够接着使用它:

>>> motorcycles = ['honda', 'yamaha', 'suzuki']
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki']
>>> popped_motorcycle = motorcycles.pop()
>>> print(motorcycles)
['honda', 'yamaha']
>>> print(popped_motorcycle)
suzuki

弹出列表中任何位置处的元素

实际上,可以使用.pop()来删除任意位置的元素,只需在圆括号中指定要删除元素的索引即可。

>>> motorcycles = ['honda', 'yamaha', 'suzuki']
>>> first_owned = motorcycle.pop(0)
print(f ' The first motorcycle I owned was a {first_owned.title()}.') 

别忘了,每当你使用pop()时,被弹出的元素就不再在列表中了。

根据值删除元素

有时候,你不知道要从列表中删除的值所处的位置。如果只知道要删除的元素的值,可使用方法.remove()

>>> motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
>>> motorcycles.remove('ducati') #此处确定'ducati'在什么位置并删除。
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki']

使用remove()方法从列表中删除元素时,也可接着使用它的值。下面删除值 ‘ducati’ 并打印一条消息,指出要将其从列表中删除的原因:

>>> motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
>>> too_expensive = 'ducati'
>>> motorcycles.remove(too_expensive)
>>> print(motorcycles)
['honda', 'yamaha', 'suzuki']
>>> print(f ' \nA {too_expensive.title()} is too expensive for me")
A Ducati is too expensive for me.

方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来确保将每个值都删除。


举报

相关推荐

0 条评论