Python列表删除的三种方法代码分享

yipeiwu_com6年前Python基础

1、使用del语句删除元素

>>> i1 = ["a",'b','c','d']
 
>>> del i1[0]
>>> print(i1)
['b', 'c', 'd']
>>>

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

2、使用pop()删除元素

  pop()可删除列表末尾的元素,并让你能够接着使用它。食欲弹出(pop)源自这样的类比:列表就是一个栈,而删除列表末尾的元素相当于弹出栈顶元素。

>>> i1 = ['cai','rui','headsome']
>>> i2 = i1.pop()
>>> print(i1)
['cai', 'rui']
>>> print(i2)
headsome
>>>

 作用:假设列表中的摩托车是按照购买时间存储的,就可以使用方法pop()打印一条消息,指出最后购买的是哪款摩托车:

#!/usr/bin/env python
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.

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

#!/usr/bin/env python
motorcycles = ['honda','yamaha','suzuki']
last_owned = motorcycles.pop(0)
print("The last motorcycle i owned was a " + last_owned.title() + '.')
========================================
The last motorcycle i owned was a Honda.

3、remove 根据值删除元素

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

注意:remove()只删除一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有的值。

以上就是本文关于Python列表删除的三种方法代码分享的全部内容,希望对大家有所帮助。欢迎参阅:Python文件的读写和异常代码示例Python网络编程详解Python中enumerate函数代码解析等,有问题请指出,感谢大家!

相关文章

Pycharm创建项目时如何自动添加头部信息

Pycharm创建项目时如何自动添加头部信息

1.打开PyCharm,选择File--Settings 2.依次选择Editor---Code Style-- File and Code Templates---Python Sc...

浅谈Series和DataFrame中的sort_index方法

Series 的 sort_index(ascending=True) 方法可以对 index 进行排序操作,ascending 参数用于控制升序或降序,默认为升序。 若要按值对 Ser...

tensorflow中next_batch的具体使用

本文介绍了tensorflow中next_batch的具体使用,分享给大家,具体如下: 此处给出了几种不同的next_batch方法,该文章只是做出代码片段的解释,以备以后查看:...

利用Python yagmail三行代码实现发送邮件

利用Python yagmail三行代码实现发送邮件

Python 发送邮件 我以前在通过Python实现自动化邮件功能的时候是这样的: import smtplib from email.mime.text import MIMET...

python实现多层感知器MLP(基于双月数据集)

python实现多层感知器MLP(基于双月数据集)

本文实例为大家分享了python实现多层感知器MLP的具体代码,供大家参考,具体内容如下 1、加载必要的库,生成数据集 import math import random impor...