# 示例代码:使用 set() 函数
# 创建一个空集合
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}
# 使用 set() 函数从字符串创建集合,每个字符作为集合的一个元素
my_string = "hello"
char_set = set(my_string)
print("从字符串创建的集合:", char_set) # 输出: 从字符串创建的集合: {'l', 'o', 'e', 'h'}
# 集合的基本操作
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集
union_set = set1.union(set2)
print("并集:", union_set) # 输出: 并集: {1, 2, 3, 4, 5}
# 交集
intersection_set = set1.intersection(set2)
print("交集:", intersection_set) # 输出: 交集: {3}
# 差集
difference_set = set1.difference(set2)
print("差集 (set1 - set2):", difference_set) # 输出: 差集 (set1 - set2): {1, 2}
set() 函数用于创建一个集合。集合是无序且不重复的元素集合。set() 会自动去除重复元素。union)、交集 (intersection) 和差集 (difference)。上一篇:python insert
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站