集合 set
集合也用花括号,但是没有映射关系!
num = {1,2,3,4,5}
>>>
>>> num = {1:'one',2:'two',3:'three'}
>>> num
{1: 'one', 2: 'two', 3: 'three'}
>>>
>>> num2 = {1,2,3,4,5,3,2,6}
>>> num2
{1, 2, 3, 4, 5, 6}
>>>
特点:
1/ 集合里的元素都是唯一的。
2 /无序,不支持索引
创建集合的方式:
1 / 直接把一堆元素用花括号括起来
2 / 使用set() 工厂函数
set()可以传入列表,也可以传入元组,但是不能传入单个元素。
>>>
>>> set1 = set([1,2,3,4,5])
>>> set1
{1, 2, 3, 4, 5}
>>> set2 = set((1,2,3,4,5,5,4))
>>> set2
{1, 2, 3, 4, 5}
>>> set3 =set(1,2,3,4,5,5,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 arguments, got 7
>>>
范例:去除列表中的重复元素
num1 = [1,2,3,4,5,5,3,1,0]
num2 =[]
for each in num1:
if each not in num2:
num2.append(each)
print(num2)
num3 = set(num1)
print(num3)
num4 = list(num3)
print(num4)
返回结果:
[1, 2, 3, 4, 5, 0]
{0, 1, 2, 3, 4, 5}
[0, 1, 2, 3, 4, 5]
添加
add()
移除
remove()
不可变集合
frozenset()
设置一个不可变集合
>>>
>>> num = frozenset([1,2,3,4,5])
>>> num
frozenset({1, 2, 3, 4, 5})
>>> num.add(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>>