在考虑多维数组作为一个例子时,有一种方法可以找到多维数组中存在的共同元素 - intersection_update()。
此方法用于查找本质上是多维的同一数组中存在的公共或相交元素。让我们考虑一个输入输出场景,然后继续编写一个程序。
考虑一个本质上是多维的二维数组。
arr = [[1, 2, 3, 4], [3, 4, 5, 6], [7, 8, 3, 4], [4, 9, 8, 3], [4, 3, 10, 12]]
上述数组包含5个子数组。
我们可以清楚地观察到元素“3”和“4”出现在“arr”的所有子数组中。
所以,元素“ 3 ”和“ 4 ”被认为是二维数组arr的公共元素。
在此示例中,我们将使用 Intersection_update() 方法查找多维数组中存在的公共元素。
考虑一个二维数组,从中可以找到公共元素。
声明一个参数化方法,以二维数组为参数,查找公共元素。
在方法中,使用0初始化set数组,并将该值赋给一个变量。
使用循环遍历数组的元素。
借助intersection_update()方法,在遍历的过程中逐个找到公共元素。
def common_elements(arr): result = set(arr[0]) for x in arr[1:]: result.intersection_update(x) return list(result) # main section if __name__ == "__main__": arr = [[1, 2, 3, 4], [3, 4, 5, 6], [7, 8, 3, 4], [4, 9, 8, 3], [4, 3, 10, 12]] res = common_elements(arr) if len(res) > 0: print ("The common elements present within the array are: ",res) else: print ("There are no common elements present within the array !!")
上述程序的输出如下 -
The common elements present within the array are: [3, 4]
NumPy的intersect1d()方法可以用来找到两个一维数组的公共元素。这类似于intersect_update()方法,它处理多维数组。为了更好地理解这个概念,让我们来看一个例子。
考虑两个本质上是一维的数组。
arr1 = [1, 2, 3, 4] arr2 = [3, 4, 5, 6]
我们可以清楚地看到元素“3”和“4”同时出现在数组arr1和arr2中。
因此,我们可以得出数组arr1和arr2的公共元素是3和4。
在下面的示例中,我们将使用numpy模块的intersect1d()方法找到多个一维数组中共同存在的元素。
import numpy as n arr1 = [1, 2, 3, 4] print("The first array is: ") print(arr1) arr2 = [3, 4, 5, 6] print("The second array is: ") print(arr2) narr1 = n.array(arr1) narr2 = n.array(arr2) print("The common elements within the given arrays are: ") print(n.intersect1d(narr1, narr2))
上述程序的输出如下 -
The first array is: [1, 2, 3, 4] The second array is: [3, 4, 5, 6] The common elements within the given arrays are: [3 4]
以此方式,根据数组的类型,可以遵循该过程。如果考虑的是多维数组,则将遵循第一个程序中的过程。
如果考虑的数组是一维数组,则将遵循第二个程序中的过程。这就是找到一个或多个数组的公共元素的方式。