#set 集合 set01 = {'UZI',369,(2,3)} print(set01,type(set01),len(set01),2 in set01,sep='====') #添加元素 集合.add set01.add('clearlove') print(set01) #删除元素 集合.remove set01.remove((2,3)) print(set01) #集合的运算 #1、交集: & ; 集合1.intersection(集合2) s1 = {'uzi','ming','the shy',123} s2 = {'uzi',123} s3 = s1 & s2 s4 = s1.intersection(s2) print(s3,s4) #2、并集: | ; 集合1.union(集合2) s5 = s1 | s2 s6 = s1.union(s2) print(s5,s6) #3、差集: 集合1-集合2 ; 集合1.difference(s2) s7 = s1 - s2 s8 = s1.difference(s2) s9 = s2 - s1 print(s7,s8,'s9:',s9) #对元素去重 list01 = [11,11,22,22,33,33,4,4,5,5] set01 = list(set(list01)) #先可以转换成集合,去重之后,再转换成列表 print(set01)
输出结果:
{369, (2, 3), 'UZI'}====<class 'set'>====3====False
{369, 'clearlove', (2, 3), 'UZI'}
{369, 'clearlove', 'UZI'}
{'uzi', 123} {'uzi', 123}
{'ming', 'uzi', 'the shy', 123} {'ming', 'uzi', 'the shy', 123}
{'ming', 'the shy'} {'ming', 'the shy'} s9: set()
[33, 4, 5, 11, 22]