# 创建一个集合
my_set = {1, 2, 3, 4, 5}
print("创建的集合:", my_set)
# 添加元素到集合
my_set.add(6)
print("添加元素后的集合:", my_set)
# 移除元素
my_set.remove(3) # 如果元素不存在会报错
print("移除元素后的集合:", my_set)
# 使用discard移除元素(如果元素不存在不会报错)
my_set.discard(7)
print("使用discard移除元素后的集合:", my_set)
# 集合的交集
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection = set1.intersection(set2)
print("交集:", intersection)
# 集合的并集
union = set1.union(set2)
print("并集:", union)
# 集合的差集
difference = set1.difference(set2)
print("差集 (set1 - set2):", difference)
# 判断子集和超集
subset = {1, 2}
superset = {1, 2, 3, 4}
print("subset 是否是 superset 的子集:", subset.issubset(superset))
print("superset 是否是 subset 的超集:", superset.issuperset(subset))
# 清空集合
my_set.clear()
print("清空后的集合:", my_set)
{}
或 set()
函数可以创建一个集合。add()
方法向集合中添加元素。remove()
和 discard()
都可以移除元素,但 remove()
在元素不存在时会抛出异常,而 discard()
不会。intersection
)、并集 (union
)、差集 (difference
) 等操作。issubset()
和 issuperset()
来判断两个集合之间的关系。clear()
方法可以清空集合中的所有元素。下一篇:查看python版本的命令
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站