一、创建集合set()
>>>set1= {1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
>>>set2 = set({1, 2, 3, 4, 5})
{1, 2, 3, 4, 5}
二、唯一性,集合内的所有元素都是唯一的,重复的元素会被删除掉
>>>set3 = {1, 2, 1, 2, 4, 3, 5}
{1, 2, 3, 4, 5}
例子:将列表 num1 = [1, 2, 3, 4, 5, 5, 3, 1, 0]中的重复元素剔除
num1 = list(set(num1))
>>>[0, 1, 2, 3, 4, 5]
三、无序性,内丝字典
四、add( )添加元素
>>>a = {1, 2, 3, 4, 5}
>>>a.add(6)
>>>a
{1, 2, 3, 4, 5, 6}
五、remove()移除元素
>>>a = {1, 2, 3, 4, 5}
>>>a.remove(5)
>>>a
{1, 2, 3, 4}
六、不可变集合 frozenset
>>>num3 = frozenset([1, 2, 3, 4, 5])
>>> num3.add(6)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
num3.add(6)
AttributeError: 'frozenset' object has no attribute 'add'