#集合 set,可变的数据类型,其中的元素是不可变有数据类型,无序,不重复
#列表转化成集合,自动就去掉重复了
set1 = set({1,2,3})
#set1 = {1,2,3,[2,3],{'name':'alex'}} 错的
print(set1) #{1, 2, 3}
#增加 add
set1 = {'alex','wusir','ritian','egon','barry'}
set1.add('女神')
print(set1) #{'egon', 'barry', '女神', 'alex', 'ritian', 'wusir'} 无序
#update
set1 = {'alex','wusir','ritian','egon','barry'}
set1.update('abc')
print(set1) #{'c', 'egon', 'barry', 'b', 'alex', 'wusir', 'ritian', 'a'}
#删除
set1 = {'alex','wusir','ritian','egon','barry'}
print(set1.pop()) #egon 随机删除
print(set1) #{'wusir', 'alex', 'barry', 'ritian'}
set1 = {'alex','wusir','ritian','egon','barry'}
set1.remove('alex') #按元素删除
print(set1) #{'egon', 'ritian', 'barry', 'wusir'}
set1.clear() #清空
print(set1) #set()
del set1 #删除整个集合
#没有更改功能
#查找
set1 = {'alex','wusir','ritian','egon','barry'}
for i in set1:
print(i)
# egon
# alex
# barry
# ritian
# wusir
#交集
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
set3 = set1 & set2
print(set3) #{4, 5}
#或者
print(set1.intersection(set2)) #{4, 5}
#并集
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
set3 = set1 | set2
print(set3) #{1, 2, 3, 4, 5, 6, 7, 8}
#或者
print(set1.union(set2)) #{1, 2, 3, 4, 5, 6, 7, 8}
#反交集
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
set3 = set1 ^ set2
print(set3) #{1, 2, 3, 6, 7, 8}
#或者
print(set1.symmetric_difference(set2)) #{1, 2, 3, 6, 7, 8}
#差集 独有的
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
set3 = set1 - set2
print(set3) #{1, 2, 3}
#或者
print(set1.difference(set2)) #{1, 2, 3}
#子集
set1 = {1,2,3}
set2 = {1,2,3,4,5,6}
print(set2 > set1) #True
#或者
print(set1.issubset(set2)) #True
#例 去掉重复的元素
li = [1,2,33,33,2,1,4,5,6,6]
set1 = set(li) #列表转换成集合
print(set1) #{1, 2, 33, 4, 5, 6}
li = list(set1) #集合转换成列表
print(li) #{1, 2, 33, 4, 5, 6}
#字符串转换成集合
s = frozenset('barry') #变成为可变类型
print(s,type(s)) #frozenset({'y', 'b', 'a', 'r'}) <class 'frozenset'> 无序
for i in s:
print(i)