集合
#集合,集合中可以使用的数据类型(str,int,float,bool,complex,tuple,frezonSet冰冻集合)
set_test = {1,2,3,4,'5','6','7','8'}
集合的操作
#集合的推导式
res = {v for v in set_test}
print(res)
'''
res:
{'7', 1, '6', 3, 4, 2, '5', '8'}
'''
#交集的操作
#求一个集合和另一个集合相交部分组成的新集合
test1 = {1,2,3,4}
test2 = {3,4,5,6}
res = test1.intersection(test2)
print(res)
'''
res:
{3, 4}
'''
#求一个集合和另一个集合相交部分组成的新集合,并把新集合赋值给第一个集合
test1 = {1,2,3,4}
test2 = {3,4,5,6}
test1.intersection_update(test2)
print(test1)
'''
test1:
{3, 4}
'''
#差集的操作
#求一个集合和另一个集合不同部分组成的新集合
test1 = {1,2,3,4}
test2 = {3,4,5,6}
#test1内有,test2内没有的
res1 = test1.difference(test2)
print(res1)
#test2内有,test1内没有的
res2 = test2.difference(test1)
print(res2)
'''
res1:
{1, 2}
res2:
{5, 6}
'''
#求一个集合和另一个集合不同部分组成的新集合,并赋值给第一个集合
test1 = {1,2,3,4}
test2 = {3,4,5,6}
#test1内有,test2内没有的
test1.difference_update(test2)
#test2内有,test1内没有的
test2.difference_update(test1)
print(test1)
print(test2)
'''
test1:
{1, 2}
test2:
{3, 4, 5, 6}
'''
#并集的操作
#求两个集合的所有的数据的组合
test1 = {1,2,3}
test2 = {3,4,5}
res = test1.union(test2)
print(res)
'''
res:
{1, 2, 3, 4, 5}
'''
#求两个集合的所有的数据的组合,并把组合赋值给第一个集合
test1 = {1,2,3}
test2 = {3,4,5}
test1.update(test2)
print(test1)
'''
test1:
{1, 2, 3, 4, 5}
'''
#对称差集的操作
#求存在于集合1中但是不存在与集合2中,和存在于集合2中但是不存在于集合1中的数据组成的集合,并赋值给第一个集合
test1 = {1,2,3,4}
test2 = {3,4,5,6}
test1.symmetric_difference_update(test2)
print(test1)
'''
test1:
{1, 2, 5, 6}
'''
集合的函数
#向集合中添加数据(直接给参数)
set_a = {1,2,3,4,5}
set_a.add('wiz')
print(set_a)
'''
set_a:
{1, 2, 3, 4, 5, 'wiz'}
'''
#随机删除集合中的一个数据
set_b = {'1',2,'3',4,5}
set_b.pop()
print(set_b)
'''
set_b:
{2, 4, 5, '3'}
'''
#删除集合中指定的元素(不存在的不删除)
set_c = {'1',2,'3',4,5}
set_c.discard('1')
print(set_c)
'''
set_c:
{'3', 2, 4, 5}
'''
#删除集合中指定的元素(不存在则报出异常)
try:
set_d = {'1',2,'3',4,5}
set_d.remove('333')
print(set_d)
except:
print('删除的元素不存在')
'''
返回:
删除的元素不存在
'''
#清空集合
set_e = {1,2,3,4,5}
set_e.clear()
print(set_e)
'''
set_e:
set()
'''
#复制集合,生成一个新的集合
sef_f = {'a','b','c'}
set_new = sef_f.copy()
print(set_new)
'''
set_f:
{'b', 'a', 'c'}
'''
set_t1 = {1,2,3,4,5,6,7}
set_t2 = {3,6}
#检测一个集合是否是另一个集合的超集
print(set_t1.issuperset(set_t2))
'''
返回:
True
'''
#检测一个集合是否是另一个集合的子集
print(set_t2.issubset(set_t1))
'''
返回:
True
'''
#检测两个集合是否相交(True不相交,False相交)
print(set_t1.isdisjoint(set_t2))
'''
返回:
False
'''
冰冻集合(frozenset)
#(1)一旦创建就无法进行任何修改的集合,就是冰冻集合
#(2)创建一个冰冻集合
icebox = frozenset({'a','b','c'})
print(icebox,type(icebox))
'''
icebox:
frozenset({'a', 'b', 'c'}) <class 'frozenset'>
'''
#(3)冰冻集合的操作:所有不涉及到修改集合本身的函数,冰冻集合都可以使用,谁是函数主体,结果就是谁的类型