Dadas dos listas de enteros, la tarea es encontrar el índice en el que el elemento de dos listas no coincide.
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.
A continuación se presentan algunas formas de lograr esta tarea.
Método #1: Usar la iteración
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)
Producción:
[1, 3]
Método #2: Usar lista de comprensión y 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)
Producción:
[1, 3]
Método #3: Usando Enumerar
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)
Producción:
[1, 3]
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA