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:
[]
给定的2个数组中没有找到明显的元素。
使用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中,那么我们将该元素追加到结果变量中,如果元素是不同的元素。同样,我们验证第二个数组元素是否存在于第一个数组中。并将不同的元素存储在结果数组中。
示例
让我们取另一组数组并找到不同的元素。
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的对称差异赋值给结果变量。然后再次使用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() 方法返回的是空集合。