在 Python 中查找两个列表中相同索引上的不匹配项
pythonserver side programmingprogramming更新于 2025/10/12 13:00:17
有时我们可能需要比较两个 Python 列表中元素的值和位置或索引。在本文中,我们将了解如何找出两个列表中相同位置上值不匹配的元素。
使用 for 循环
我们可以设计 for 循环来比较相似索引处的值。如果值不匹配,则我们将索引添加到结果列表中。 for 循环首先获取第一个索引中的值,然后使用 if 条件将其与第二个列表中的值进行比较。
示例
listA= [13, 'Mon',23, 62,'Sun']
listB = [5, 'Mon',23, 6,'Sun']
# 索引变量
idx = 0
# 结果列表
res = []
# 使用迭代
for i in listA:
if i != listB[idx]:
res.append(idx)
idx = idx + 1
# 结果
print("The index positions with mismatched values:\n",res)
输出
运行上述代码得到以下结果 −
The index positions with mismatched values: [0, 3]
使用 zip
zip 函数可帮助我们在比较每个索引中的元素时编写更短的代码。元素值不匹配的位置的索引值将被捕获。
示例
listA= [13, 'Mon',23, 62,'Sun']
listB = [5, 'Mon',23, 6,'Sun']
res = [listB.index(n) for m, n in
zip(listA, listB) if n != m]
# 结果
print("The index positions with mismatched values:\n",res)
输出
运行上述代码得到以下结果 −
The index positions with mismatched values: [0, 3]
使用枚举
它与 zip 函数中的方法类似,不同之处在于,在将枚举函数应用于列表之一时,我们使用 for 循环来遍历每个元素和索引。
示例
listA= [13, 'Mon',23, 62,'Sun']
listB = [5, 'Mon',23, 6,'Sun']
res = [idx for idx, elem in enumerate(listB)
if elem != listA[idx]]
# 结果
print("The index positions with mismatched values:\n",res)
输出
运行上述代码得到以下结果 −
The index positions with mismatched values: [0, 3]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

