集合与字典非常的相似也是用大括号来表示的,但是不同的是字典中含有键和键值,而集合中就像只含有键一样。
>>> a = {1,2,3,4,5,6}
>>> type(a)
<class 'set'>
>>>
集合的作用就是唯一,集合会把重复的元素删除,并且集合不支持索引
>>> a = {1,2,3,4,5,4,3,2,1}
>>> a
{1, 2, 3, 4, 5}
>>> a[1]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
a[1]
TypeError: 'set' object does not support indexing
>>>
集合的创建方法有两种
一种是直接把一堆元素用大括号(花括号)括起来
另一种是使用set()工厂函数
>>> set1 = set([1,2,3,5,4,5])
>>> set1
{1, 2, 3, 4, 5}
>>>
集合元素的添加和移除add()和remove()
>>> set1
{1, 2, 3, 4, 5}
>>> 1 in set1
True
>>> set1.add(6)
>>> set1
{1, 2, 3, 4, 5, 6}
>>> set1.remove(1)
>>> set1
{2, 3, 4, 5, 6}
>>>
定义不可变的集合frozenset()
>>> num3 = frozenset([1,23,4,5,5])
>>> num3.add(0)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
num3.add(0)
AttributeError: 'frozenset' object has no attribute 'add'
>>>