python集合的并集、交集_Python 集合set()添加删除、交集、并集、集合操作详解
1、在Python中set是基本數據類型的一種集合類型,它有可變集合(set())和不可變集合(frozenset)兩種。創建集合set、集合set添加、集合刪除、交集、并集、差集的操作都是非常實用的方法。
創建集合set
python set類是在python的sets模塊中
set('boy')
set(['y', 'b', 'o'])
集合添加、刪除
python 集合的添加有兩種常用方法,分別是add和update。
集合add方法:是把要傳入的元素做為一個整個添加到集合中,例如:
a = set('boy')
a.add('python')
a
set(['y', 'python', 'b', 'o'])
集合update方法:是把要傳入的元素拆分,做為個體傳入到集合中,例如:
a = set('boy')
a.update('python')
a
set(['b', 'h', 'o', 'n', 'p', 't', 'y'])
集合刪除操作方法:remove
set(['y', 'python', 'b', 'o'])
a.remove('python')
a
set(['y', 'b', 'o'])
set集合是無序的,不能通過索引和切片來做一些操作。
2、
1》交集
x={1,2,3,4}
y={3,4,5,6}
x
set([1, 2, 3, 4])
y
set([3, 4, 5, 6])
x&y
set([3, 4])
x.intersection(y)
set([3, 4])
2》并集
x | y #集合并集
set([1, 2, 3, 4, 5, 6])
x.union(y)
set([1, 2, 3, 4, 5, 6])
3》差集
x-y # x與y的差集
set([1, 2])
x.difference(y)# x與y的差集
set([1, 2])
y-x # y與x的差集
set([5, 6])
y.difference(x)# y與x的差集
set([5, 6])
4》對稱差集
x^y
set([1, 2, 5, 6])
y^x
set([1, 2, 5, 6])
x.symmetric_difference(y)
set([1, 2, 5, 6])
y.symmetric_difference(x)
set([1, 2, 5, 6])
5》集合的子集和超集
x
set([1, 2, 3, 4])
z
set([1, 2, 3])
z.issubset(x)#z是x的子集
True
x.issuperset(z)#x是z的超集
True
下面的圖片形象地展示了set集合的各種運算:
image
集合 x <==> ① + ②
集合 y <==> ② + ③
交集 x&y <==> ②
并集 x|y <==> ① + ② + ③
差集 x-y <==> ①
差集 y-x <==> ③
對稱差集 x^y == y^x <==> ① + ③
總結
以上是生活随笔為你收集整理的python集合的并集、交集_Python 集合set()添加删除、交集、并集、集合操作详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nacos 配置不会动态刷新_Aliba
- 下一篇: decimal函数python_deci