前言
五一快乐!!!
哈哈哈,终归是逍遥先行,抽个时间把最近有意思的一个东西分享一下,所谓是一个坑的大汇总
列表删除的坑
-
通过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)
集合删除的坑
集合和字典都是迭代时不能改变大小,方法类似
最后的最后,五一快乐,我继续逍遥了!!!