Dadas 2 listas, agregue los elementos que faltan de la lista 1 a la lista 2.
Entrada : test_list1 = [5, 6, 4, 8, 9, 1], test_list2 = [9, 8, 10]
Salida : [5, 6, 4, 1, 9, 8, 10]
Explicación : 5, 6, 4, 1 agregado a la lista 2, en orden.Entrada : test_list1 = [5, 6, 4, 8, 9, 1], test_list2 = [9, 10]
Salida : [5, 6, 4, 8, 1, 9, 10]
Explicación : 5, 6, 4, 8, 1 agregado a la lista 2, en orden.
Método #1: Usar la comprensión de listas
En esto, iteramos la lista 1 para verificar los elementos faltantes en la lista 2, luego agregamos estos elementos a la lista 2.
Python3
# Python3 code to demonstrate working of # Append Missing elements from other List # Using list comprehension # initializing list test_list1 = [5, 6, 4, 8, 9, 1] test_list2 = [9, 8, 7] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # extracting elements from list 1 which are not in list 2 temp1 = [ele for ele in test_list1 if ele not in test_list2] # constructing result res = temp1 + test_list2 # printing result print("The modified list 2 : " + str(res))
The original list 1 is : [5, 6, 4, 8, 9, 1] The original list 2 is : [9, 8, 7] The modified list 2 : [5, 6, 4, 1, 9, 8, 7]
Método #2: Usar set() + operador “-” + extender()
En esto, verificamos los elementos de la lista 1 que faltan en la lista 2 usando el operador set() y – y extend() se usa para unir la lista y obtener el resultado deseado.
Python3
# Python3 code to demonstrate working of # Append Missing elements from other List # Using set() + "-" operator + extend() # initializing list test_list1 = [5, 6, 4, 8, 9, 1] test_list2 = [9, 8, 7] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # finding missing words rem_list = (set(test_list1) - set(test_list2)) # checking order res = [ele for ele in test_list1 if ele in rem_list] # joining result res.extend(test_list2) # printing result print("The modified list 2 : " + str(res))
The original list 1 is : [5, 6, 4, 8, 9, 1] The original list 2 is : [9, 8, 7] The modified list 2 : [5, 6, 4, 1, 9, 8, 7]
Publicación traducida automáticamente
Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA