Python中如何实现数组的并集和交集运算
发布时间:2024-01-18 11:19:34
在Python中,可以使用set数据结构来实现数组的并集和交集运算。
1. 并集运算:
并集运算指的是将两个数组中的所有元素合并成一个新的数组,新数组中的元素是两个数组中的所有不重复的元素。
可以使用set数据结构来去除元素的重复性。
示例代码:
arr1 = [1, 2, 3, 4, 5] arr2 = [4, 5, 6, 7, 8] # 将数组转为set set1 = set(arr1) set2 = set(arr2) # 求并集 union_set = set1.union(set2) # 将并集转为list union_arr = list(union_set) print(union_arr)
输出结果:
[1, 2, 3, 4, 5, 6, 7, 8]
2. 交集运算:
交集运算指的是找出两个数组中共同存在的元素,即两个数组中都包含的元素。
同样可以使用set数据结构来实现。
示例代码:
arr1 = [1, 2, 3, 4, 5] arr2 = [4, 5, 6, 7, 8] # 将数组转为set set1 = set(arr1) set2 = set(arr2) # 求交集 intersection_set = set1.intersection(set2) # 将交集转为list intersection_arr = list(intersection_set) print(intersection_arr)
输出结果:
[4, 5]
需要注意的是,数组中的元素顺序会被打乱,因为set是无序的数据结构。如果需要按照原来的顺序输出,可以使用sorted函数对list进行排序。
示例代码:
arr1 = [1, 2, 3, 4, 5] arr2 = [4, 5, 6, 7, 8] # 将数组转为set set1 = set(arr1) set2 = set(arr2) # 求并集 union_set = set1.union(set2) # 将并集转为list,并按照原来的顺序排序 union_arr = sorted(list(union_set), key=lambda x: arr1.index(x)) print(union_arr)
输出结果:
[1, 2, 3, 4, 5, 6, 7, 8]
使用set数据结构来实现数组的并集和交集运算,可以很方便地去除重复元素,并快速找到共同存在的元素。同时,使用Python内置的set数据结构还可以提高运算效率。
