【python】set集合基础与使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014636245/article/details/87925773

set 是python中一种不常用,但某些场景下很有用的数据类型

1.set的创建

python中集合有两种方式创建,一种是利用大括号{set...}的形式,另一种是利用set()函数形式。

set1 = {1,2,3,4,5}
print('set1 is ',type(set1))
set2 = {1,'string'}
print('set2 is ',type(set2))

#use set()
set3 = set('strinnnnng')
set4 = set(['string1','string2','string3'])

print(set3)
print(set4)

"""
>>>
set1 is  <class 'set'>
set2 is  <class 'set'>
{'g', 'n', 's', 'i', 'r', 't'}     #无序,n不重复
{'string2', 'string1', 'string3'}  #set(函数只能包含单一的一整个元素,可放入一个list,将其中每个字符串元素作为集合元素
"""

从上面的结果可以看到,set具有无序、元素不重复等特点。(集合的每一个元素是不可变元素,如整数,字符串、元组)

2.set的操作

seta = set('abcdefg')
setb = {'abc'}

print(seta)

#增加元素
seta.add('w')
print(seta)

#随机删除元素
seta.pop()
print(seta)

#删除指定元素
setb.add('c')
print(setb)
setb.remove('c')
print(setb)
#方法二
setb.discard('a')  #不存在不报错
print(setb)

"""
>>>
{'e', 'd', 'a', 'g', 'b', 'f', 'c'}
{'e', 'd', 'a', 'g', 'b', 'f', 'c', 'w'}  #w新增了
{'d', 'a', 'g', 'b', 'f', 'c', 'w'}       #随机pip了d
{'c', 'abc'}                              #setb新增c
{'abc'}                                   #删除了c
{'abc'}                                   #没有a,discard()也不报错
"""


3.集合运算

seta = set('abcdefghijk')
setb = set('abcd')
setc = set('lmnopqrst')

#子集
print(setb<seta)   #小于号表示是否是子集,成立则为true
print(setc<seta)
"""
>>>
True
False
"""

#交集
print(seta & setb)    #利用&操作
print(seta.intersection(setb))   #利用集合内置函数intersection()
"""
>>>
{'d', 'a', 'c', 'b'}
{'d', 'a', 'c', 'b'}
"""

#并集
print(seta | setc)    #利用 | 操作得到并集
print(seta.union(setc))  #利用内置函数union()
"""
>>>
{'q', 'r', 'p', 'f', 's', 'm', 't', 'e', 'c', 'i', 'd', 'l', 'a', 'b', 'n', 'k', 'g', 'h', 'j', 'o'}
{'q', 'r', 'p', 'f', 's', 'm', 't', 'e', 'c', 'i', 'd', 'l', 'a', 'b', 'n', 'k', 'g', 'h', 'j', 'o'}
"""

#差集
print(seta - setb)
print(seta.difference(setb))
"""
>>>
{'f', 'e', 'j', 'g', 'h', 'i', 'k'}
{'f', 'e', 'j', 'g', 'h', 'i', 'k'}
"""

#对称差,只属于其中一个集合的元素
setd = set('abxyz')
print(setb ^ setd)    #利用 ^ 操作得到,类似于异或操作
print(setb.symmetric_difference(setd))  #利用内置函数symmetric_difference()
"""
>>>
{'c', 'x', 'd', 'y', 'z'}    #共有的ab被剔除
{'c', 'x', 'd', 'y', 'z'}    #cd只在setb中,xyz只在setd中存在
"""

ref:
https://www.jdoodle.com/python3-programming-online
http://www.cnblogs.com/suendanny/p/8597596.html
http://www.iplaypy.com/jichu/set.html
http://www.runoob.com/python3/python3-set.html


在这里插入图片描述
pic from pexels.com

猜你喜欢

转载自blog.csdn.net/u014636245/article/details/87925773
今日推荐