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

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




motorcycles[0] = 'ducati', .append(), .insert(), del motorcycles[0], .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()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来确保将每个值都删除。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值