python8 集合
集合
介绍
- Python内置的数据结构
- 和列表、字典一样都属于可变类型的序列
- 集合是没有Value的字典,【即 只存在Key】
- 类型:set
创建
- 直接 {} 创建,用 ,号 分隔
- 内置函数set
例:
# 作者:咸瑜
# 代码时间:2022/11/12
# 创建集合
# 元素不允许重复 [重复的被替换]
# 那么其实内部也貌似是用hash来算的
test = {1, 2, 3, 4, 1, 5, 6, 7}
print(test, type(test)) # {1, 2, 3, 4, 5, 6, 7} <class 'set'>
# set函数的多种创建方法:
test = set(range(6))
print(test, type(test)) # {0, 1, 2, 3, 4, 5} <class 'set'>
print(set([6, 5, 4, 3])) # {3, 4, 5, 6}
print(set((6, 5, 4, 3))) # {3, 4, 5, 6}
print(set('咸瑜好帅')) # {'好', '咸', '帅', '瑜'}
print(set({77, 88, 99, 11})) # {88, 99, 11, 77}
print({}, type({})) # {} <class 'dict'>
print(set(), type(set())) # set() <class 'set'>
相关操作
判断
- is
- not in
新增
- add() 方法,一次添加一个元素
- updata方法,至少添加一个元素
删除
- remove() 方法,一次删除一个指定元素,不存在抛异常 KeyError
- discard() 方法,一次删除一个指定元素,不存在不抛异常!!!!
- pop()方法,一次只删除一个任意元素
- clear()方法,清空集合
例:
# 作者:咸瑜
# 代码时间:2022/11/13
# 集合的相关操作
test = {1, 2, 3, 4, 1, 5, 6, 7}
# 判断
print(1 in test) # True
print(11 in test) # False
print(1 not in test) # False
print(11 not in test) # True
# 添加
test.add(66)
print(test)
test.update({77, 88, 99})
print(test)
# 删除
test.remove(66)
# test.remove(0) # 报异常
print(test)
test.discard(77)
test.discard(0) # 不报异常
print(test)
test.pop() # 没有参数!!
test.pop() # 随机删除 删除那个元素我也不知道
print(test)
test.clear()
print(test)
集合间的关系
只要是元素相等就是True,顺序不等也是True 例:
# 作者:咸瑜
# 代码时间:2022/11/13
# 集合的相关操作
test = {1, 2, 3}
test1 = {3, 2, 1}
test2 = {4}
print(test == test1) # True
print(test != test1) # False
# 判断test 是不是 其他集合 的超集
print(test.issuperset(test1)) # True
print(test.issuperset(test2)) # False
# 两个集合是否含有交集 有交集False 没交集为True
print(test.isdisjoint(test1), '?') # False
print(test.isdisjoint(test2)) # True
集合的数学操作
# 作者:咸瑜
# 代码时间:2022/11/13
test = {1, 2, 3}
test2 = {2, 4, 6}
# 交集操作
print(test.intersection(test2)) # 运行结果:{2}
print(test & test2) # intersection 和 & 是一样的 # 运行结果:{2}
# 并集操作
print(test.union(test2)) # 运行结果: {1, 2, 3, 4, 6}
print(test | test2) # union 和 | 一样效果 #运行结果: {1, 2, 3, 4, 6}
# 差集
print(test.difference(test2)) # 运行结果: {1,3}
print(test - test2) # difference 和 - 效果一样 # 运行结果: {1,3}
# 对称差集
print(test.symmetric_difference(test2)) # 运行结果: {1, 3, 4, 6}
print(test ^ test2) # symmetric_difference 和 ^ 效果一样,运行结果: {1, 3, 4, 6}
集合生成式
# 作者:咸瑜
# 代码时间:2022/11/13
test = {i * i for i in range(1, 11)}
print(test) # {64, 1, 4, 36, 100, 9, 16, 49, 81, 25}
列表、字典、元祖、集合 总结
本文来自博客园,作者:咸瑜,转载请注明原文链接:https://www.cnblogs.com/bi-hu/p/16885733.html