# 创建一个空的集合
empty_set = set()
print(empty_set) # 输出: set()
# 使用set()将列表转换为集合,自动去重
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set) # 输出: {1, 2, 3, 4, 5}
# 添加元素到集合
my_set.add(6)
print(my_set) # 输出: {1, 2, 3, 4, 5, 6}
# 移除集合中的元素
my_set.remove(3)
print(my_set) # 输出: {1, 2, 4, 5, 6}
# 集合的交集操作
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection = set1.intersection(set2)
print(intersection) # 输出: {3, 4}
# 集合的并集操作
union = set1.union(set2)
print(union) # 输出: {1, 2, 3, 4, 5, 6}
# 集合的差集操作
difference = set1.difference(set2)
print(difference) # 输出: {1, 2}
上一篇:python queue
下一篇:python注释符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站