# Python中集合的运算示例
# 创建两个集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 并集运算
union_set = set1.union(set2) # 或者使用 set1 | set2
print("并集:", union_set) # 输出: 并集: {1, 2, 3, 4, 5, 6, 7, 8}
# 交集运算
intersection_set = set1.intersection(set2) # 或者使用 set1 & set2
print("交集:", intersection_set) # 输出: 交集: {4, 5}
# 差集运算 (set1 - set2)
difference_set = set1.difference(set2) # 或者使用 set1 - set2
print("差集 (set1 - set2):", difference_set) # 输出: 差集 (set1 - set2): {1, 2, 3}
# 对称差集运算 (set1 和 set2 中不同时存在的元素)
symmetric_difference_set = set1.symmetric_difference(set2) # 或者使用 set1 ^ set2
print("对称差集:", symmetric_difference_set) # 输出: 对称差集: {1, 2, 3, 6, 7, 8}
这段代码展示了如何在Python中进行集合的基本运算,包括并集、交集、差集和对称差集。
上一篇:python遍历文件夹中的文件
下一篇:代码编程python
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站