本文共 3028 字,大约阅读时间需要 10 分钟。
集合是一个无序的、不重复的元素序列。集合中的每个元素都是独特的,即集合中不允许出现重复的元素。集合的主要作用是进行成员关系测试以及去除重复元素。
在Python中,可以使用大括号 {} 或 set() 函数来创建集合。
# 使用大括号创建集合s1 = {1, 2, 3, 4, 5}print(s1) # 输出:{1, 2, 3, 4, 5}# 使用set()函数创建集合s2 = set([1, 2, 2, 3, 4, 4, 5])print(s2) # 输出:{1, 2, 3, 4, 5},重复元素被自动去除 # 创建空字典empty = {}print(type(empty)) # 输出: ,空字典用花括号表示# 创建空集合empty_set = set()print(type(empty_set)) # 输出: ,空集合用set()函数创建 集合提供了多种基本操作,如添加、删除元素、计算交集、并集、差集等。这些操作使集合在处理去重、成员检测等任务时非常有用。
在Python中,add() 方法用于向集合中添加元素。如果元素已存在于集合中,add() 方法不会改变集合。
# 创建一个空集合s = set()# 添加元素s.add(1)s.add(2)s.add(3)# 打印集合print(s) # 输出:{1, 2, 3}# 重复添加已存在的元素不会改变集合s.add(2) # 集合保持不变print(s) # 输出:{1, 2, 3} remove() 方法用于从集合中删除指定元素。如果元素不存在,会抛出 KeyError 异常。为了避免异常,可以使用 discard() 方法,它不会在元素不存在时抛出错误。
# 创建一个集合s = {1, 2, 3, 4}# 删除元素s.remove(3) # 集合变为 {1, 2, 4}print(s) # 输出:{1, 2, 4}# 尝试删除不存在的元素会抛出 KeyError# s.remove(5) # 这会抛出 KeyError# 安全删除不存在的元素s.discard(5) # 没有输出,集合保持不变# 再次打印集合print(s) # 输出:{1, 2, 4} 集合支持以下基本运算:
使用 & 运算符或 intersection() 方法计算两个集合的交集。
# 创建两个集合set1 = {1, 2, 3, 4, 5}set2 = {4, 5, 6, 7, 8}# 使用 & 运算符计算交集intersection_using_and = set1 & set2print("交集:", intersection_using_and) # 输出:{4, 5}# 使用 intersection() 方法计算交集intersection_using_method = set1.intersection(set2)print("交集:", intersection_using_method) # 输出:{4, 5} 使用 | 运算符或 union() 方法计算两个集合的并集。
set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}# 使用 | 运算符计算并集print(set1 | set2) # 输出:{1, 2, 3, 4, 5, 6}# 使用 union() 方法计算并集print(set1.union(set2)) # 输出:{1, 2, 3, 4, 5, 6} 使用 - 运算符或 difference() 方法计算两个集合的差集。
set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}# 使用 - 运算符计算差集print(set1 - set2) # 输出:{1, 2}# 使用 difference() 方法计算差集print(set1.difference(set2)) # 输出:{1, 2} 使用 ^ 运算符或 symmetric_difference() 方法计算两个集合的对称差集。
set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}# 使用 ^ 运算符计算对称差集print(set1 ^ set2) # 输出:{1, 2, 5, 6}# 使用 symmetric_difference() 方法计算对称差集print(set1.symmetric_difference(set2)) # 输出:{1, 2, 5, 6} 除了上述基本操作,集合还提供了一些常用方法,如 isdisjoint() 和 issubset()。
isdisjoint() 方法用于判断两个集合是否无交集。
set1 = {1, 2, 3}set2 = {3, 4, 5}# 判断是否无交集no_intersection = set1.isdisjoint(set2)print("是否无交集:", no_intersection) # 输出:False# 判断是否是子集is_subset = set1.issubset(set2)print("是不是子集:", is_subset) # 输出:False,因为 set1 中的元素不全在 set2 中# 也可以使用 <= 运算符判断子集关系is_subset_operator = set1 <= set2print("是不是子集(使用运算符):", is_subset_operator) # 输出:False 集合可以与列表、元组等其他数据类型进行转换,非常适合用于数据处理任务。
s = {1, 2, 3, 4}list_s = list(s)print(list_s) # 输出:[1, 2, 3, 4] s = {1, 2, 3, 4}tuple_s = tuple(s)print(tuple_s) # 输出:(1, 2, 3, 4) list_s = [1, 2, 2, 3, 4, 4]set_s = set(list_s)print(set_s) # 输出:{1, 2, 3, 4} tuple_s = (1, 2, 3, 4)set_s = set(tuple_s)print(set_s) # 输出:{1, 2, 3, 4} 通过以上内容,可以看出集合在Python中是一个非常有用的数据类型。它的成员检测速度快、元素唯一性保证,适用于去重、快速查找等场景。
转载地址:http://snofk.baihongyu.com/