Python 基础【第七篇】集合

时间:2021-01-23 05:56:02

一、集合的概念:

不同元素的集合

二、集合的方法:

方法

用法

范例

set()

过滤掉重复 设置成为集合

>>> subset=set([1,1,2,3,4,4,6])

>>> subset

set([1, 2, 3, 4, 6]) //集合中剔除了重复的值 这里剔除了1,4

>>> type(subset) //查看subset类型为set集合

<type 'set'>

subset_1 &subset_2

求交集

>>> subset_1 =set([1,2,3,4,5,6])

>>> subset_2 =set([1,3,4,6])

>>> subset_1 & subset_2

set([1, 3, 4, 6])

subset_1 | subset_2

求并集

>>> subset_1 =set([1,2,3,4,5,6])

>>> subset_2 =set([1,3,6,9,10])

>>> subset_1 | subset_2

set([1, 2, 3, 4, 5, 6, 9, 10])

subset_1 ^ subset_2

求反交集

>>> subset_1 =set([1,2,3,4,5,6])

>>> subset_2 =set([1,3,6,9,10])

>>> subset_1 ^ subset_2

set([2, 4, 5, 9, 10])

subset_1 – subset_2

剔除所有set2集合中有的值

>>> subset_1 =set([1,2,3,4,5,6])

>>> subset_2 =set([1,3,6,9,10])

>>> subset_1 - subset_2

set([2, 4, 5])

subset_1.issubset(subset_2)

判断subset_1是否为subset_2的子集,是则返回 True 否则返回Flase

>>> subset_1 = set([1, 2, 3, 4, 5, 6])

>>> subset_2 = set([1, 3, 4])

>>> subset_1.issubset(subset_2)

False

>>> subset_2.issubset(subset_1)

True

subset_1.issuperset(subset_2)

判断subset_1是否为subset_2的父集,是则返回 True 否则返回Flase

>>> subset_1 = set([1, 2, 3, 4, 5, 6])

>>> subset_2 = set([1, 3, 4])

>>> subset_1.issuperset(subset_2)

True

set.remove(value)

删除集合set中的value值

>>> subset_1 = set([1, 2, 3, 4, 5, 6])

>>> subset_1.remove(4)

>>> subset_1

set([1, 2, 3, 5, 6])

subset.update(value)

更新集合将value更新到集合

>>> subset = set([1,2,5])

>>> subset.update([5,6,7])

>>> subset

set([1, 2, 5, 6, 7])