从列表中删除元素的方法

您所在的位置:网站首页 从列表中删除元素的方法有哪些 从列表中删除元素的方法

从列表中删除元素的方法

2024-04-02 09:29| 来源: 网络整理| 查看: 265

在列表中删除元素可以使用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()只删除第一个指定的值,如果删除的值在列表中多次出现的话,就需要使用循环判断来进行多次删除



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3