zoukankan      html  css  js  c++  java
  • 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()只删除一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有的值。

  • 相关阅读:
    [转]只有程序员才能看懂的幽默
    论安防集成管理平台规范标准建设的重要性和必要性
    视频集成技术演进与创新实践
    (转)jQuery中Ajax事件beforesend及各参数含义
    (转)如何打一手好Log
    marquee标签
    如何学习Git,如何使用Git
    学习vue
    python安装教程
    Jmeter压力测试(入门篇)
  • 原文地址:https://www.cnblogs.com/caicairui/p/7550868.html
Copyright © 2011-2022 走看看