# 示例代码:使用 Python 的 set() 函数
# 创建一个空的集合
empty_set = set()
print("创建一个空的集合:", empty_set)
# 从列表创建集合,自动去除重复元素
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print("从列表创建集合并去除重复元素:", my_set)
# 添加元素到集合
my_set.add(6)
print("添加元素到集合:", my_set)
# 移除集合中的元素
my_set.remove(3) # 如果元素不存在会抛出 KeyError
print("移除集合中的元素:", my_set)
# 使用 discard 方法移除元素(不会抛出异常)
my_set.discard(7) # 如果元素不存在也不会报错
print("使用 discard 方法移除元素:", my_set)
# 集合运算
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # 并集
print("两个集合的并集:", union_set)
intersection_set = set1.intersection(set2) # 交集
print("两个集合的交集:", intersection_set)
difference_set = set1.difference(set2) # 差集
print("两个集合的差集:", difference_set)
symmetric_difference_set = set1.symmetric_difference(set2) # 对称差集
print("两个集合的对称差集:", symmetric_difference_set)
set() 函数用于创建一个新的集合。add() 方法向集合中添加元素。remove() 或 discard() 方法可以移除集合中的元素,区别在于 remove() 在元素不存在时会抛出异常,而 discard() 不会。上一篇:python闭包
下一篇:python 定义函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站