# Python set 用法示例
# 创建一个空的 set
empty_set = set()
print("创建空集合:", empty_set)
# 使用 {} 创建一个包含元素的 set
my_set = {1, 2, 3, 4, 5}
print("创建包含元素的集合:", my_set)
# 添加元素到 set 中
my_set.add(6)
print("添加元素后的集合:", my_set)
# 移除 set 中的元素
my_set.remove(3) # 如果元素不存在会抛出 KeyError
print("移除元素后的集合:", my_set)
# 使用 discard 方法移除元素,如果元素不存在不会抛出异常
my_set.discard(7)
print("使用 discard 方法移除元素后的集合:", my_set)
# 清空 set
my_set.clear()
print("清空后的集合:", my_set)
# 集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 并集
union_set = set1.union(set2)
print("并集:", union_set)
# 交集
intersection_set = set1.intersection(set2)
print("交集:", intersection_set)
# 差集
difference_set = set1.difference(set2)
print("差集 (set1 - set2):", difference_set)
# 对称差集
symmetric_difference_set = set1.symmetric_difference(set2)
print("对称差集:", symmetric_difference_set)
# 检查子集和超集
subset_check = {1, 2}.issubset(set1)
superset_check = set1.issuperset({1, 2})
print("检查子集:", subset_check)
print("检查超集:", superset_check)
set() 可以创建一个空的集合。{} 可以直接创建包含元素的集合。add() 方法用于向集合中添加单个元素。remove() 和 discard() 方法都可以移除集合中的元素,但 remove() 在元素不存在时会抛出异常,而 discard() 不会。clear() 方法可以清空集合。union)、交集 (intersection)、差集 (difference) 和对称差集 (symmetric_difference) 等操作。issubset() 和 issuperset() 分别用于检查一个集合是否是另一个集合的子集或超集。上一篇:python 字典取值
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站