集合函数:intersection、union和difference等
发布时间:2023-06-01 13:06:56
集合函数是在Python中用于操作集合的一些函数,常用的有intersection(交集)、union(并集)和difference(差集)等。
1. intersection(交集)
交集是指两个集合中都存在的元素构成的新集合。在Python中,可以使用intersection()函数来返回两个集合的交集。
示例代码:
set1 = {1, 2, 3, 4}
set2 = {2, 3, 5, 6}
intersection = set1.intersection(set2)
print(intersection)
输出结果为:
{2, 3}
解释:set1和set2都包含2和3,因此它们的交集为{2, 3}。
2. union(并集)
并集是指两个集合中所有元素构成的新集合。在Python中,可以使用union()函数来返回两个集合的并集。
示例代码:
set1 = {1, 2, 3, 4}
set2 = {2, 3, 5, 6}
union = set1.union(set2)
print(union)
输出结果为:
{1, 2, 3, 4, 5, 6}
解释:set1和set2的并集为{1, 2, 3, 4, 5, 6},因为它们合并后包含了所有的元素。
3. difference(差集)
差集是指两个集合中一个集合存在而另一个集合不存在的元素构成的新集合。在Python中,可以使用difference()函数来返回两个集合的差集。
示例代码:
set1 = {1, 2, 3, 4}
set2 = {2, 3, 5, 6}
difference = set1.difference(set2)
print(difference)
输出结果为:
{1, 4}
解释:set1中存在但set2中不存在的元素为{1, 4},因此它们的差集为{1, 4}。
除了这三个常用的集合函数,Python中还有一些其他的集合函数,如symmetric_difference()(返回两个集合的对称差集)、issubset()(判断一个集合是否是另一个集合的子集)等。这些函数在操作集合时非常有用。
