# Python set() 函数用法示例
# 创建一个空的集合
empty_set = set()
print("创建一个空的集合:", empty_set)
# 使用 set() 函数从列表创建集合,自动去重
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print("从列表创建集合并去重:", my_set)
# 使用 set() 函数从字符串创建集合,自动去重字符
my_string = "hello"
char_set = set(my_string)
print("从字符串创建集合并去重字符:", char_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, 4}
set2 = {3, 4, 5, 6}
intersection = set1.intersection(set2)
print("集合的交集操作:", intersection)
# 集合的并集操作
union = set1.union(set2)
print("集合的并集操作:", union)
# 集合的差集操作
difference = set1.difference(set2)
print("集合的差集操作:", difference)
set()
可以创建一个空的集合。set()
函数将列表转换为集合,并自动去除重复元素。set()
函数将字符串转换为集合,并自动去除重复字符。add()
方法向集合中添加元素。remove()
方法移除集合中的元素。如果元素不存在会抛出 KeyError
异常。discard()
方法移除元素,即使元素不存在也不会抛出异常。intersection()
方法获取两个集合的交集。union()
方法获取两个集合的并集。difference()
方法获取两个集合的差集。希望这些示例和解释能帮助你更好地理解 set()
函数的用法。
上一篇:用python画玫瑰花
下一篇:python更新命令
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站