3.6 集合
集合(set) --- 只存储字典的key
1.集合的定义
-格式: {元素}
-特征:
1.无序 2.无重复 3.可为任意类型
1.集合的定义
#- 创建空集合
'''set = {}
print(type(set)) <class 'dict'> 因为空的 {} 被用来表示空字典,而不是空集合。'''
set1 = set()
print(set1) #set()
print(type(set1)) #<class 'set'>
# - 创建一个元素集合
set1 = {10}
print(set1) #{10}
print(type(set1)) #<class 'set'>
# - 创建多个元素集合
set1 = {"username","password",10.0,98,98}
print(set1) #{10.0, 'password', 'username', 98} 证明了集合的无序和无重复性
# - 案例:对某个字符串去重
string1 = "hellow world"
print(set(string1)) #{'h', 'r', ' ', 'w', 'd', 'e', 'o', 'l'}
2.集合的常用方法
Clear,remove,copy
add:添加元素,如果元素重复,不能添加,涉及到hash算法
difference:差集
intersection:交集
union:并集
update:更新集合,合并集合
discard:移除元素,但是元素如果不存在,则不做任何操作
2.测试集合的常用函数
# - add
print(set1.add("age")) #None 无返回值
print(set1) #{98, 10.0, 'password', 'age', 'username'}
# - update 更新并合并集合,如果重复则覆盖
print(set1.update({"hellow world"})) #输出一个字典会打印一整个元素
print(set1) #{'hellow world', 98, 'age', 10.0, 'password', 'username'}
print(set1.update("hellow world")) #输出一个字符串会拆分开并去重加入集合
print(set1) #{'e', 'hellow world', 98, 'age', 10.0, 'l', 'o', 'r', 'd', 'password', 'w', ' ', 'h', 'username'}
# - discard 删除一个元素
set2 = {"wzw",23,22,"hello"}
print(set2.discard("hello"))
print(set2) #{'wzw', 23, 22}
# -intersection 交集
set_x = {1,2,3,4,5}
set_y = {1,2,3,6,7}
print(set_x.intersection(set_y)) #{1, 2, 3}
# -union 并集
print(set_x.union(set_y)) #{1, 2, 3, 4, 5, 6, 7}
# -difference 差集
print(set_x.difference(set_y)) #{4, 5} x关于y的差集
print(set_y.difference(set_x)) #{6, 7} y关于x的差集