Python中如何获取两个集合的并集
发布时间:2024-01-08 02:05:18
在Python中,可以使用union()函数来获取两个集合的并集。union()函数返回一个新集合,其中包含两个集合中的所有元素,但不重复。并集运算符|也可以用于获取两个集合的并集。
下面是两个使用例子:
**例子1:**
# 使用union()函数获取两个集合的并集
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print("并集:", union_set) # 输出: 并集: {1, 2, 3, 4, 5}
# 使用并集运算符获取两个集合的并集
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print("并集:", union_set) # 输出: 并集: {1, 2, 3, 4, 5}
在上面的例子中,首先创建了两个集合set1和set2。然后使用union()函数获取了两个集合的并集,结果存储在union_set变量中,并打印出来。接下来使用并集运算符|同样获取了两个集合的并集,并打印出来。
**例子2:**
# 获取两个集合的并集的实际应用
students_1 = {"Alice", "Bob", "Charlie"}
students_2 = {"Charlie", "Dave", "Eve"}
# 使用union()函数获取两个集合的并集
all_students = students_1.union(students_2)
print("所有学生:", all_students) # 输出: 所有学生: {'Eve', 'Dave', 'Alice', 'Charlie', 'Bob'}
# 使用并集运算符获取两个集合的并集
all_students = students_1 | students_2
print("所有学生:", all_students) # 输出: 所有学生: {'Eve', 'Dave', 'Alice', 'Charlie', 'Bob'}
在上面的例子中,首先创建了两个集合students_1和students_2,分别表示两个班级的学生。然后使用union()函数获取了两个集合的并集,并将结果存储在all_students变量中,并打印出来。接下来使用并集运算符|同样获取了两个集合的并集,并打印出来。输出结果显示了所有学生的姓名。
