一、集合类型
1、set集合。为可变集合,元素可更改。不能作为集合元素。
2、frozenset集合。为不可变集合,元素不能更改。可作为集合元素。
二、集合的特点
1、元素互异。赋值时,能够自动删除重复的元素。
2、元素无序。
---两个集合相等,只要元素相同即可
---不能通过索引访问元素
三、创建集合的方法
1、使用大括号创建set集合。如:
a={1,2,3,4,1} #a={1,2,3,4}
2、使用set函数创建set集合。如:
a=set( ) #创建空的set集合
b=set([1,2,3,4] #a={1,2,3,4}
3、使用frozenset函数创建frozenset集合。如:
a=frozenset( ) #创建空的frozenset集合
a=frozenset([1,2,3,4]) #a=frozenset({1, 2, 3, 4})
四、集合的基本操作
1、元素的访问
---由于集合的元素是无序的,因此不能通过索引访问。
---可遍历集合元素:
a=set([1,2,3,4])
for i in a:
print(i)
2、元素存在性判断
通过in、not in操作符可判断元素是否在集合中。如:
print("OK") if 2 in a else print("NO")
3、集合类型的操作符
---联合(|)。二个集合的元素放在一起组成新集合。
如:{1,2}|{2,3}得到{1,2,3}
---交集(&)。二个集合的相同元素组成新集合。
如:{1,2}&{2,3}得到{2}
---差补(-)。从左侧集合中删除与右侧集合相同的元素后得到新集合。
如:{1,2}-{2,3}得到{1}
---对称差分(^)。在二个集合中选择不共有的元素组成的新集合。
如:{1,2}^{2,3}得到{1,3}
***不同的集合类型可以运算,得到的新集合的类型与左侧集合的类型相同。
4、可变集合的操作符
(1)|=:联合更新。如:a|={1,2}
(2)&=:交集更新。如:a&={1,2}
(3)-=:差补更新。如:a-={1,2}
(4)^=:对称差分更新。如:a^={1,2}
五、set集合的内置函数
1、add(e):追加元素e。如:
a=set( ) #创建空的set集合
a.add(1) #a={1}
2、clear( ):清空集合。
3、copy( ):创建集合副本。
4、difference(other):返回一个新集合,该集合的元均不在other的任意集合中。
如:a={1,2,3,4},则a.difference({2,3})的返回值为{1,4}。
5、difference_update(other):从集合中删除与other共有的元素。
如:a={1,2,3,4},则a.difference_update({2,3})后a={1,4}。
6、discard(e):从集合中删除元素e。不存在e不会触发错误。
7、intersection(other):返回与other集合的交集得到的新集合。
如:a={1,2},则a.intersection({2,3})返回一个新集合{2}
8、intersection_update(other):与other的交更新集合。
如:a={1,2},则a.intersection_update({2,3})后a={2}
9、isdisjoint(other):如果与集合other无公共元素,返回True。否则返回False。
10、issubset(other):是否为other的子集。是,返回True;否,返回False
11、issuperset(other):other是否为子集。是,返回True;否,返回False
12、pop():删除任意一个元素并返回该元素值。集合为空时触发KeyError错误。
13、remove(e):删除元素e。e不存在时触发KeyError错误。
14、symmetric_difference(other):在二个集合的并中删除共有元素后得到的新集合。
如:a={1,2,3},则a.symmetric_difference({2,3,4})的返回值为{1,4}
15、symmetric_difference_update(other):在二个集合的并中删除共有元素后更新集合。
如:a={1,2,3},则a.symmetric_difference_update({2,3,4})后a={1,4}
16、union(other):返回与other的并集。
如:a={1,2,3},则a.union({1,4})的返回值为{1,2,3,4}
17、update(other):与other的并集更新集合。
如:a={1,2,3},则a.update({1,4})后,a={1,2,3,4}
六、frozenset集合的内置函数
frozenset集合的内置函数有:copy、difference、intersection、isdisjoint、issubset、issuperset、symmetric_difference、union。使用方法请参阅set集合。

