集合:可变的数据类型,他里面的元素必须是不可变的数据类型

特点:1、无序

     2、不重复

1、set定义

# 使用set定义
set1 = set({1, 2, 3})
# 直接使用括号定义
set1 = {1, 2, 3}
# 空集合定义方式,直接写{}会定义成字典
set1 = set({})
print(set1, type(set1))  # set()空集合结果显示为set(),空字典显示为{}

错误示范:

# 因为列表、字典是可变数据类型,报错
# TypeError: unhashable type: 'list'
set2 = {1, 2, 3, [2, 3], {'name': 'alex'}}
print(set2, type(set2))

2、增

set1.add('Gigi')  # Gigi做为一个元素增加
print(set1)

set1.update('abc')  # 拆分为最小元素,添加到集合{'b', 'beer', 'a', 'c'....}
print(set1)

update类似list的extend

3、删

print(set1.pop())  # 随机删除,本返回值
print(set1)

set1.remove('beer')  # 按照元素删除
print(set1)

set1.clear()  # 清空集合
print(set1)  # set()

del set1  # 从内存中删除,删除后set1不存在
print(set1)

4、查

for i in set1:
    print(i)

5、集合的操作

# 交集,set1和set2所共有
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = set1 & set2
print(set3)
print(set1.intersection(set2))

# 合集,set1和set2全部元素的集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 | set2)
print(set1.union(set2))

# 反交集,set1和set2不共有的元素
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 ^ set2)
print(set1.symmetric_difference(set2))

# 差集,set1有,而set2没有
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 - set2)
print(set1.difference(set2))

# 子集,set1的所有元素是不是在set2中,是返回True
set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5, 6}
print(set1 < set2)
print(set1.issubset(set2))

# 超级,set2是否包含set1的所有元素,是返回True
print(set2 > set1)
print(set2.issuperset(set1))

6、冻结集合

set2 = {1, 2, 3, 4, 5, 6}
s = frozenset(set2)
print(s, type(s))
print(s, type(s))
print(s, type(s))
print(s, type(s))
# frozenset({1, 2, 3, 4, 5, 6}) <class 'frozenset'>

frozenset方法,使集合冻结。冻结后,顺序不会发生改变,类型为:<class 'frozenset'>

02-12 22:09