使用set()函数进行集合运算的方法

   2024-09-30 4080
核心提示:set() 函数在 Python 中用于创建一个集合(set),它是一个无序的不重复元素序列。集合支持多种运算,如并集、交集、差集等。以

set() 函数在 Python 中用于创建一个集合(set),它是一个无序的不重复元素序列。集合支持多种运算,如并集、交集、差集等。以下是一些常见的集合运算方法:

创建集合:
# 使用 set() 函数创建空集合empty_set = set()# 使用 set() 函数从列表或元组创建集合my_list = [1, 2, 3, 4, 5, 5]my_set = set(my_list)  # 结果为 {1, 2, 3, 4, 5}
并集(Union):
set1 = {1, 2, 3}set2 = {3, 4, 5}# 使用 | 运算符计算并集union_set = set1 | set2# 或者使用 union() 方法union_set = set1.union(set2)
交集(Intersection):
set1 = {1, 2, 3}set2 = {3, 4, 5}# 使用 & 运算符计算交集intersection_set = set1 & set2# 或者使用 intersection() 方法intersection_set = set1.intersection(set2)
差集(Difference):
set1 = {1, 2, 3}set2 = {3, 4, 5}# 使用 - 运算符计算差集difference_set = set1 - set2# 或者使用 difference() 方法difference_set = set1.difference(set2)
对称差集(Symmetric Difference):
set1 = {1, 2, 3}set2 = {3, 4, 5}# 使用 ^ 运算符计算对称差集symmetric_difference_set = set1 ^ set2# 或者使用 symmetric_difference() 方法symmetric_difference_set = set1.symmetric_difference(set2)
判断子集(Subset)和超集(Superset):
set1 = {1, 2, 3}set2 = {1, 2, 3, 4, 5}# 使用 <= 运算符判断子集is_subset = set1 <= set2# 或者使用 issubset() 方法is_subset = set1.issubset(set2)# 使用 >= 运算符判断超集is_superset = set2 >= set1# 或者使用 issuperset() 方法is_superset = set2.issuperset(set1)
添加元素:
my_set = {1, 2, 3}# 使用 add() 方法添加元素my_set.add(4)
删除元素:
my_set = {1, 2, 3, 4}# 使用 remove() 方法删除元素my_set.remove(4)

这些是使用 set() 函数进行集合运算的一些基本方法。你可以根据需要进行更多的操作。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号