集合基础用法
# 集合
# 关系运算
# 1.作用
# 1.1 关系运算 寻找共同好友 for循环 此种方式比较麻烦
from re import M, S
my_friends = ["egon","tom","jason"]
his_friends = ["egon","tom","jack"]
l=[]
for x in my_friends:
if x in his_friends:
l.append(x)
print(l)
'''
2. 定义:在{}内用逗号分隔开多个元素,多个元素需要满足以下三个条件
1.集合内元素必须为不可变类型
2.集合内元素无序
3.集合内元素没有重复
定义空集合 a=set()
a={} 类型为字典
'''
a= {1,2,3,4,5,1,'list','sb'}
print(type(a),a)
# 3.类型转换
a = set('hello world')
print(a)
# 4.内置方法
my_friends = {"egon","tom","jason"}
his_friends = {"egon","tom","jack"}
# 4.1 取交集:取两者共同的好友
togither_friends = my_friends & his_friends
print(togither_friends)
print(my_friends.intersection(his_friends)) # 内置函数
# # 4.2 取合集 :两者共同的好友
togither_friends = my_friends | his_friends
print(togither_friends)
print(my_friends.union(his_friends))
# # 4.3 取my_friends共同的好友
print(my_friends-his_friends)
print(my_friends.difference(his_friends))
# # 取his_friends共同的好友
print(his_friends-my_friends)
print(my_friends.difference(his_friends))
# 4.4 对称差集:求两个用户独有的好友们
print(my_friends ^ his_friends)
print(my_friends.symmetric_difference(his_friends))
# 4.5 父子集:包含关系
s1 = {1,2,3}
s2 = {1,2}
print(s1>s2) # 当s1大于或等于s2时,才能说s1是s2的爹
print(s1.issuperset(s2))
# s1 = {1,2,3}
# s2 = {1,2,3}
# print(s1==s2) # 当s1=s2时,互为父子
'''
去重
1.只能对不可变类型去重
2.无法保证原来的顺序
所以我们基本不会用集合去重
'''
l=[
{'name':'wangxue','age':18,'sex':'male'},
{'name':'wangjing','age':28,'sex':'male'},
{'name':'bob','age':38,'sex':'female'},
{'name':'wangxue','age':18,'sex':'male'},
]
new_l = []
for k in l:
if k not in new_l:
new_l.append(k)
print(new_l)
# discard和remove区别 discard:删除一个不存在的元素不会报错,容错性更好
s = {1,2,3}
s.discard(4)
# s.remove(4)
print(s)
# update追加
s.update({1,3,4,'hello'})
print(s)