来源
http://www.mcgzjx.com
http://8k.hlkjfj.com
http://r.hlkjfj.com
http://s.hlkjfj.com
http://tiyu.hlkjfj.com
在Python中,并集(Union)是指两个或多个集合中所有不重复元素的集合。它是集合论中的一个基本概念,在Python中通过union()
方法或|
运算符实现。
对于集合A和B,它们的并集A ∪ B定义为:
A ∪ B = {x | x ∈ A 或 x ∈ B}
即包含所有属于A或属于B的元素。
在Python中,集合(set)是一种无序的不重复元素序列。我们可以使用:
set1.union(set2)
方法set1 | set2
运算符来获取两个集合的并集。
A ∪ B
图示:蓝色和绿色圆分别代表两个集合,整个有色区域代表它们的并集
# 创建两个集合 setA = {1, 2, 3, 4} setB = {3, 4, 5, 6} # 使用union()方法 union_set = setA.union(setB) print(union_set) # 输出: {1, 2, 3, 4, 5, 6}
# 使用 | 运算符 union_set_operator = setA | setB print(union_set_operator) # 输出: {1, 2, 3, 4, 5, 6}
setC = {5, 6, 7, 8} # 多个集合的并集 multi_union = setA.union(setB, setC) print(multi_union) # 输出: {1, 2, 3, 4, 5, 6, 7, 8} # 使用运算符 multi_union_operator = setA | setB | setC print(multi_union_operator) # 输出: {1, 2, 3, 4, 5, 6, 7, 8}
特性 | union()方法 | | 运算符 |
---|---|---|
可读性 | 较高,明确表达意图 | 简洁,但需了解运算符 |
多个集合操作 | 支持,setA.union(setB, setC, ...) | 支持,setA | setB | setC |
与其他数据类型 | 可接受任何可迭代对象 | 只能用于集合类型 |
链式调用 | 支持 | 支持 |
性能 | 略慢 | 略快 |
合并多个来源的数据并去除重复项:
# 从不同来源获取的用户ID列表 users_source1 = [101, 102, 103, 104, 105] users_source2 = [103, 104, 105, 106, 107] users_source3 = [107, 108, 109, 110] # 合并并去重 all_users = set(users_source1).union(users_source2, users_source3) print(sorted(all_users)) # 输出: [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]
组合多个标签以获取所有相关项目:
# 商品标签系统 electronics = {'laptop', 'smartphone', 'tablet'} accessories = {'headphones', 'charger', 'case'} popular = {'smartphone', 'headphones', 'tablet'} # 获取电子产品和配件中受欢迎的商品 result = electronics.union(accessories) & popular print(result) # 输出: {'smartphone', 'headphones', 'tablet'}
合并用户的多组权限:
# 用户权限组 admin_perms = {'create', 'update', 'delete'} editor_perms = {'create', 'update'} viewer_perms = {'read'} # 用户拥有编辑和查看权限 user_perms = editor_perms.union(viewer_perms) print(user_perms) # 输出: {'create', 'update', 'read'}
intersection()
或 &
运算符difference()
或 -
运算符symmetric_difference()
或 ^
运算符集合的并集操作时间复杂度平均为O(n),对于大型数据集,使用集合操作比列表操作更高效。
Python中的并集操作是处理集合数据的强大工具,主要特点包括:
union()
方法或|
运算符获取两个或多个集合的并集掌握并集操作将大大提高你处理数据集和关系运算的效率,是Python编程中必备的基础技能。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。