Python程序:查找两个数组中不同的元素
在编程中,数组是一种用于存储同构数据元素集合的数据结构。数组中的每个元素都由一个键或索引值标识。
Python中的数组
Python没有特定数据类型来表示数组。相反,我们可以使用列表作为数组。
[1, 4, 6, 5, 3]
查找两个数组中不同的元素意味着识别两个给定数组之间唯一的元素。
输入输出场景
假设我们有两个包含整数值的数组A和B。结果数组将包含两个数组中不同的元素。
Input arrays: A = [1, 2, 3, 4, 5] B = [5, 2, 6, 3, 9] Output array: [1, 6, 4, 9]
元素1、6、4、9是这两个数组之间唯一的值。
Input arrays: A = [1, 2, 3, 4, 5] b = [3, 4, 5, 1, 2] Output array: []
在给定的两个数组中没有找到不同的元素。
使用for循环
我们将对元素数量相等的数组使用for循环。
示例
在下面的示例中,我们将使用列表推导方法定义for循环。
arr1 = [1, 2, 3, 4, 5]
arr2 = [5, 2, 6, 3, 9]
result = []
for i in range(len(arr1)):
if arr1[i] not in arr2:
result.append(arr1[i])
if arr2[i] not in arr1:
result.append(arr2[i])
print("The distinct elements are:", result)
输出
The distinct elements are: [1, 6, 4, 9]
在这里,我们使用for循环和if条件找到了不同的元素。最初,迭代循环并验证元素arr1[i]是否不存在于数组arr2中,如果元素是不同的元素,我们将把该元素添加到result变量中。同样,我们将第二个数组元素与第一个数组进行了验证。并将不同的元素存储在result数组中。
示例
让我们再取一组数组并找到不同的元素。
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 1, 2]
result = []
for i in range(len(a)):
if a[i] not in b:
result.append(a[i])
if b[i] not in a:
result.append(b[i])
print("The distinct elements are:", result)
输出
The distinct elements are: []
在给定的数组集中没有找到不同的元素。
使用集合
在两个数组中查找不同的元素与查找两个集合之间的对称差非常相似。通过使用Python集合数据结构及其属性,我们可以很容易地识别两个数组中不同的元素。
示例
首先,我们将列表转换为集合,然后在两个集合之间应用对称差属性^以获得不同的元素。
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7, 8]
result = list((set(a) ^ set(b)))
if result:
print("The distinct elements are:", result)
else:
print("No distinct elements present in two arrays")
输出
The distinct elements are: [1, 2, 6, 7, 8]
我们还可以使用set.symmetric_difference()方法查找两个数组中不同的元素。symmetric_difference()方法返回给定集合中所有唯一的项。
语法
set_A.symmetric_difference(set_B)
示例
让我们看一个例子,从两个数组中获取不同的元素。
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7, 8]
result = list(set(a).symmetric_difference(set(b)))
if result:
print("The distinct elements are:", result)
else:
print("No distinct elements present in two arrays")
输出
The distinct elements are: [1, 2, 6, 7, 8]
在这里,我们使用了symmetric_difference()方法将A和B的对称差添加到result变量中。然后,使用list()函数将唯一的元素集合再次转换为列表。
示例
如果没有找到不同的元素,则symmetric_difference()方法将返回空集。
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 1, 2]
result = list(set(a).symmetric_difference(set(b)))
if result:
print("The distinct elements are:", result)
else:
print("No distinct elements present in two arrays")
输出
No distinct elements present in two arrays
在上面的示例中,所有元素都是公共元素。因此,symmetric_difference()方法返回空集。
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP