栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python列表、字典、集合删除的坑

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python列表、字典、集合删除的坑

文章目录
    • 前言
    • 列表删除的坑
    • 字典删除的坑
    • 集合删除的坑

前言

五一快乐!!!
哈哈哈,终归是逍遥先行,抽个时间把最近有意思的一个东西分享一下,所谓是一个坑的大汇总

列表删除的坑
  • 通过for循环,不使用clear()删除列表元素

  • 尝试一:

    lst = [1, 2, 3, 4]
    for i in lst:
        lst.pop()   #[1, 2]
    print(lst)
    

  • 尝试二:

    lst = [1, 2, 3, 4]
    for i in lst:
        lst.pop(0)   #[3, 4]
    print(lst)
    

  • 尝试三:

    lst = [1, 2, 3, 4]
    for i in lst:
        lst.remove(i)  #[2, 4]
    print(lst)
    

  • 成功方法

    lst = [1, 2, 3, 4]
    for i in range(len(lst)):
        lst.pop()   #[]
    print(lst)
    
    lst = [1, 2, 3, 4]
    for i in range(len(lst) - 1, -1, -1):
        del lst[i]  #[]
    print(lst)
    
    lst = [1, 2, 3, 4]
    for i in range(len(lst)):
        del lst[-1]  #[]
    print(lst)
    
    lst = [1, 2, 3, 4]
    lst1 = lst.copy()
    for i in lst1:
        lst.remove(i)   #[]
    print(lst)
    去尾成功,去头列表会自动向前补充
    
字典删除的坑
  • 常规思路

    dic = dict.fromkeys("12345", 1) #字典在迭代时不能改变大小
    for i in dic:
        dic.pop(i)  
    print(dic)  #dictionary changed size during iteration
    
  • 正确方法:

    dic = dict.fromkeys("12345", 1)
    dic1 = dic.copy()
    for i in dic1:
        dic.pop(i)
    print(dic)
    
集合删除的坑

集合和字典都是迭代时不能改变大小,方法类似

最后的最后,五一快乐,我继续逍遥了!!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/850237.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号