zoukankan      html  css  js  c++  java
  • python中的del,remove,pop有什么区别

    python中有3个删除元素的方法:del remove pop

    虽然它们都是删除元素,用于删除列表、字符串等里面的元素,但是用法可不完全一样,元组由于是不可变的,所以不能使用哦!那么接下来就来看看它们之间有什么区别:

    # 代码源列表如下:
    a_list = ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']

    1. del——指定索引值删除

    # del 列表[索引值]
    del a_list[1]
       
    # 源列表:
    ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']
    
    # del删除数据后的列表:
    ['Mecell', 'Python', True, None, [1, 2, 3], 'Python']  
    

    2. remove——默认移除第一个出现的元素

    # 列表.remove[删除对象] 
    # 对象可以是列表里面的任何数据类型:字符串、数字、bool等
    a_list.remove['Python']
    
    # 源列表:
    ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']
    # remove删除数据后的列表:
    ['Mecell', 18, True, None, [1, 2, 3], 'Python']
    
    从结果可以看出,列表里面有两个'Python',但是实际上只是删除了第一个,最后一个并没有删除,这就是remove的特点,需要大家注意!    
    

      

    3. pop——括号内不添加索引值,则默认删除列表中的最后一个元素;反之则默认根据索引值删除 

    # 列表.pop() --删除最后一个元素
    a_list.pop()
    
    # 源列表:
    ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']
    # pop删除数据后的列表:
    ['Mecell', 18, 'Python', True, None, [1, 2, 3]]
    
    
    # 列表.pop(索引值) --指定索引值删除
    a_list.pop(3) 
    # 源列表: ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python'] # pop删除数据后的列表: ['Mecell', 18, 'Python', None, [1, 2, 3], 'Python']

      

    以上就是del,remove和pop的用法区别啦!

  • 相关阅读:
    两个数组的交集
    左叶子之和
    下载安装python
    占位
    2020 软件工程实践 助教总结
    安装使用 QEMU-KVM 虚拟化环境(Arch Linux / Manjaro / CentOS / Ubuntu )
    #69. 新年的QAQ
    1097E. Egor and an RPG game(Dilworth定理)
    #553. 【UNR #4】己酸集合
    #2099. 「CQOI2015」标识设计(插头dp)
  • 原文地址:https://www.cnblogs.com/mecell224/p/11116839.html
Copyright © 2011-2022 走看看