集合:可变的数据类型,它里面的元素必须是不可变的数据类型,无序,不重复
# 创建方法:1.set1 = set({1,2,3}) 2.set1 = {}
# 增 随机增加
set1 = {'jack','tom','join','jin'}
set1.add('刘')
print(set1)
set1.update('abc')
print(set1)
# 删
set1 = {'jack','tom','join','jin'}
print(set1.pop()) # 随机删除,有返回值
print(set1)
set1.remove('jack') # 按元素去删
print(set1)
set1.clear() # 清空集合
print(set1)
del set1 # 删除整个集合
print(set1)
# 查
set1 = {'jack','tom','join','jin'}
for i in set1:
print(i)
# 没有改,但可以求交集,并集等
set2 ={1,2,3,4,6}
set3 ={1,2,7,8,9}
print(set2 & set3) # (交集)或者print(set2.intersection(set3))
print(set2 | set3) # (并集)或者print(set2.union(set3))
print(set2 ^ set3) # (反交集)或者print(set2.symmetric_difference(set3))
print(set2 - set3) # (差集)或者print(set2.difference(set3)),意思是set2里面独有的
print(set2 < set3) # (子集)或者print(set2.issubset(set3)),意思是set3里面包含了set2
print(set2 > set3) # (超集)或者print(set2.issuperset(set3))
# 去重
例子:去除列表中重复的数字li=[1,2,2,3,4,5,5,77,77,9]
li = [1,2,2,3,4,5,5,77,77,9]
set1 = set(li)
li = list(set1)
print(li)
# 变成不可变数据类型,也是无序
set4 = frozenset('jack')
print(set4,type(set4))
深浅copy
# 1.浅拷贝只是在内存中重新创建了开辟了一个空间存放一个新列表,但是新列表中的元素与原列表中的元素是公用的。
# 同一代码块下:
l1 = [1, '天空', True, (1,2,3), [22,33]]
l2 = l1.copy()
print(id(l1),id(l2)) # 2713214468360 2713214524680
print(id(l1[-2]),id(l2[-2])) # 2547618888008 2547618888008
print(id(l1[-1]),id(l2[-1])) # 2547620322952 2547620322952
# 不同代码块下(终端操作):
l1 = [1, '天空', True, (1, 2, 3), [22, 33]]
l2 = l1.copy()
print(id(l1), id(l2)) # 1477183162120 1477183162696
print(id(l1[-2]), id(l2[-2])) # 1477181814032 1477181814032
print(id(l1[-1]), id(l2[-1])) # 1477183162504 1477183162504
# 2.深拷贝deepcopy。
# 同一代码块下
import copy
l1 = [1, 'alex', True, (1,2,3), [22,33]]
l2 = copy.deepcopy(l1)
print(id(l1), id(l2)) # 2788324482440 2788324483016
print(id(l1[0]),id(l2[0])) # 1470562768 1470562768
print(id(l1[-1]),id(l2[-1])) # 2788324482632 2788324482696
print(id(l1[-2]),id(l2[-2])) # 2788323047752 2788323047752
# 不同代码块下(终端操作)
import copy
l1 = [1, '天空', True, (1, 2, 3), [22, 33]]
l2 = copy.deepcopy(l1)
print(id(l1), id(l2)) # 1477183162824 1477183162632
print(id(0), id(0)) # 1470562736 1470562736
print(id(-2), id(-2)) # 1470562672 1470562672
print(id(l1[-1]), id(l2[-1])) # 1477183162120 1477183162312
循环删除
# 列表
li = [1,2,3,4,5]
lst2 = li.copy()
for w in lst2:
li.remove(w)
print(li)
# 字典
dic = {'name':'jack','age':18,'hobby':'game'}
lst = []
for w in dic.keys():
lst.append(w)
for w in lst:
dic.pop(w)
print(dic)
删除含有K的键值对
# 方法1
dic1 = {'k1':'v1','k2':'v2','k3':'v3','a1':'v4'}
dic1_1 = {}
for i in dic1.keys():
if 'k' not in i:
dic1_1.setdefault(i,dic1[i])
dic1 = dic1_1
print(dic1)
# 方法2
dic1 = {'k1':'v1','k2':'v2','k3':'v3','a1':'v4'}
li = []
for i in dic1:
if 'k' in i:
li.append(i)
for i in li:
del dic1[i]
print(dic1)
# 转化为bool值
# 除了0,'',[],{},(),set(),里面为空就是F,其余都是T