1、集合的定义
由不同元素组成
无序
集合中的元素必须是不可变类型
集合具有去重性即集合中的元素是不可以重复的
>>> s = {1, 2, 3}
>>> s1 = set("Hello")
>>> print(s, s1)
{1, 2, 3} {'l', 'e', 'H', 'o'}
2、集合元素的添加
s = {1, 2, 3, 4, 5, 6}
s.add("s")
s.add(3)
print(s)
>>>
{1, 2, 3, 4, 5, 6, 's'}
3、集合元素的删除
s = {1, 2, 3, 4, 5, 6}
# 随机删除
s.pop()
s.pop()
print(s)
>>>
{3, 4, 5, 6}
# 指定元素删,不存在会报错
s.remove(3)
print(s)
>>>
{4, 5, 6}
# 指定元素删,不存在不会报错
s.discard(1)
s.discard(23)
print(s)
>>>
{4, 5, 6}
4、集合的运算
p_1 = {'shi', 'fdfd', 'trony'}
l_1 = {'shi', 'fdfd', '123'}
# 取交集
print(p_1.intersection(l_1))
print(p_1&l_1)
>>>
{'shi', 'fdfd'}
{'shi', 'fdfd'}
# 求并集
print(p_1.union(l_1))
print(p_1 | l_1)
>>>
{'shi', '123', 'trony', 'fdfd'}
{'shi', '123', 'trony', 'fdfd'}
# 求差集
print(p_1 - l_1)
print(l_1 - p_1)
print(l_1.difference(p_1))
print(p_1.difference(l_1))
>>>
{'trony'}
{'123'}
{'123'}
{'trony'}
5、不可变集合
s1 = frozenset("hello")
print(s1)
>>>
frozenset({'e', 'o', 'h', 'l'})