集合

'''
集合中的元素是无序不可重复
集合分为可变集合和不可变集合
'''
print("====================集合定义开始=======================")
# 创建空集合
s = set()
s = frozenset()
# 可变集合
s = {1, 2, 3}
print(s, type(s))
# 不可变集合
fs = frozenset("abc")
print(fs, type(fs))
# 转变集合
s = set("aabc")
print(s, type(s))
s = set([1, 2, 3])
print(s, type(s))
s = set((1, 2, 3))
print(s, type(s))

print("====================集合定义结束=======================")
print("====================集合推导式开始=======================")
# 可变集合
s = {ele for ele in range(10)}
print(s, type(s))

# 不可变集合
fs = frozenset(ele for ele in range(10))
print(fs, type(fs))
print("====================集合推导式结束=======================")
print("====================集合curd开始=======================")
# 新增   集合中的元素都不可变,所以不能添加列表,字典
s = {1, 2, 3}
s.add(4)
print(s, type(s))
# 删除,元素不存在,返回错误,想不报错,请用discard
ret = s.remove(4)
print(ret, s)
ret = s.discard(5)
print(ret, s)
ret = s.pop()  # 随机删除
print(ret, s)
# ret = s.clear()
print(ret, s)  # 清空集合

# 修改,不存在的

# 遍历
for ele in s:
    print(ele)

for ele in iter(s):
    print(ele)

print("====================集合curd结束=======================")
print("====================集合的交并差操作开始=======================")
s = {1, 2, 3, 4, 5}
s1 = {3, 4, 5, 6, 7, 8}
# 交集
print(s.intersection(s1), s, s1)
print(s & s1, s, s1)
# 并集
print(s.union(s1))
print(s | s1)
# 差集
print(s.difference(s1), s, s1)
print(s1.difference(s), s, s1)
print(s - s1)
print(s1 - s)
print("====================集合的交并差操作结束=======================")
print("====================集合的判定开始=======================")
# 两个集合不相交
s2 = {2, 3}
print(s.isdisjoint(s1))

# 一个集合包含另一个集合
print(s.issuperset(s2))
# 一个集合包含于另一个集合
print(s2.issubset(s))

print("====================集合的判定结束=======================")

你可能感兴趣的:(集合)