Python|在两个列表中的同一索引上查找不匹配项
给定两个整数列表,任务是找到两个列表的元素不匹配的索引。
Input:
Input1 = [1, 2, 3, 4]
Input2 = [1, 5, 3, 6]
Output: [1, 3]
Explanation:
At index=1 we have 2 and 5 and at index=3
we have 4 and 6 which mismatches.
以下是实现此任务的一些方法。
方法#1:使用迭代
Python3
# Python code to find the index at which the
# element of two list doesn't match.
# List initialisation
Input1 = [1, 2, 3, 4]
Input2 = [1, 5, 3, 6]
# Index initialisation
y = 0
# Output list initialisation
Output = []
# Using iteration to find
for x in Input1:
if x != Input2[y]:
Output.append(y)
y = y + 1
# Printing output
print(Output)
Python3
# Python code to find the index at which the
# element of two list doesn't match.
# List initialisation
Input1 = [1, 2, 3, 4]
Input2 = [1, 5, 3, 6]
# Using list comprehension and zip
Output = [Input2.index(y) for x, y in
zip(Input1, Input2) if y != x]
# Printing output
print(Output)
Python3
# Python code to find the index at which the
# element of two list doesn't match.
# List initialisation
Input1 = [1, 2, 3, 4]
Input2 = [1, 5, 3, 6]
# Using list comprehension and enumerate
Output = [index for index, elem in enumerate(Input2)
if elem != Input1[index]]
# Printing output
print(Output)
输出:
[1, 3]
方法 #2:使用列表理解和 zip
Python3
# Python code to find the index at which the
# element of two list doesn't match.
# List initialisation
Input1 = [1, 2, 3, 4]
Input2 = [1, 5, 3, 6]
# Using list comprehension and zip
Output = [Input2.index(y) for x, y in
zip(Input1, Input2) if y != x]
# Printing output
print(Output)
输出:
[1, 3]
方法#3:使用枚举
Python3
# Python code to find the index at which the
# element of two list doesn't match.
# List initialisation
Input1 = [1, 2, 3, 4]
Input2 = [1, 5, 3, 6]
# Using list comprehension and enumerate
Output = [index for index, elem in enumerate(Input2)
if elem != Input1[index]]
# Printing output
print(Output)
输出:
[1, 3]