利用set()函数实现在Python中的集合交并差运算
发布时间:2024-01-09 14:50:12
在Python中,可以使用set()函数来创建一个集合。集合是一个无序的、不可重复元素的集合,可以实现集合的交、并、差运算。
1. 集合的创建和基本操作:
使用set()函数可以创建一个空集合:
empty_set = set()
也可以将一个可迭代对象转化为集合:
numbers = set([1, 2, 3, 4, 5])
集合中的元素是 的,重复的元素会被自动去除:
numbers = set([1, 2, 2, 3, 3, 4, 5])
print(numbers) # 输出:{1, 2, 3, 4, 5}
2. 集合的交运算:
集合的交运算可以使用&符号,或者调用intersection()方法:
set1 = set([1, 2, 3, 4, 5])
set2 = set([3, 4, 5, 6, 7])
intersection = set1 & set2
print(intersection) # 输出:{3, 4, 5}
intersection = set1.intersection(set2)
print(intersection) # 输出:{3, 4, 5}
3. 集合的并运算:
集合的并运算可以使用|符号,或者调用union()方法:
set1 = set([1, 2, 3, 4, 5])
set2 = set([3, 4, 5, 6, 7])
union = set1 | set2
print(union) # 输出:{1, 2, 3, 4, 5, 6, 7}
union = set1.union(set2)
print(union) # 输出:{1, 2, 3, 4, 5, 6, 7}
4. 集合的差运算:
集合的差运算可以使用-符号,或者调用difference()方法:
set1 = set([1, 2, 3, 4, 5])
set2 = set([3, 4, 5, 6, 7])
difference = set1 - set2
print(difference) # 输出:{1, 2}
difference = set1.difference(set2)
print(difference) # 输出:{1, 2}
使用这些运算,可以方便地对集合进行交、并、差运算,实现各种集合操作。
以下是一个完整的示例,展示了如何使用set()函数进行集合运算:
set1 = set([1, 2, 3, 4, 5])
set2 = set([3, 4, 5, 6, 7])
intersection = set1 & set2
print(intersection) # 输出:{3, 4, 5}
union = set1 | set2
print(union) # 输出:{1, 2, 3, 4, 5, 6, 7}
difference = set1 - set2
print(difference) # 输出:{1, 2}
上述代码定义了两个集合set1和set2,然后进行了交、并、差运算,并输出结果。输出结果为:
{3, 4, 5}
{1, 2, 3, 4, 5, 6, 7}
{1, 2}
通过使用set()函数和相应的集合运算符或方法,可以方便地实现集合的交、并、差运算。这些运算在处理数据的过程中非常有用,可以快速、高效地完成集合操作。
