从列表中删除元素的方法

在列表中删除元素可以使用del、方法pop()、方法remove()。

使用del删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

del motorcycles[0]
print(motorcycles)

其结果应该为

['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']

del可以删除任何位置处的列表元素,条件是知道其索引。

使用方法pop()删除元素

如果需要将列表中的元素删除,并接着使用它的值,则可以使用pop。方法pop()可以删除列表末尾的元素并且能够接着使用它。

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

其结果应为

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki

下面一例则介绍了怎样将pop()之后的元素进行使用

motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")

输出为

The last motorcycle I owned was a Suzuki.

但实际上也可以使用pop()来删除任何位置的元素,只需要在括号中加入要删除的元素索引即可。

使用方法remove()删除元素

与前两种方法不同的是,remove()是根据元素的值来进行删除而非索引。

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

结果为

['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

从remove()中删除的元素,也可以继续使用它的值。

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.

需要注意的是,remove()只删除第一个指定的值,如果删除的值在列表中多次出现的话,就需要使用循环判断来进行多次删除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值