Python | Combinar elementos de sublistas

Dadas dos listas que contienen sublistas, la tarea es fusionar elementos de la sublista de dos listas en una sola lista.

Ejemplos:

Input:
list1 = [[1, 20, 30],
         [40, 29, 72], 
         [119, 123, 115]]

list2 = [[29, 57, 64, 22],
         [33, 66, 88, 15], 
         [121, 100, 15, 117]]

Output: [[1, 20, 30, 29, 57, 64, 22],
         [40, 29, 72, 33, 66, 88, 15],
         [119, 123, 115, 121, 100, 15, 117]]

 
Método #1: UsarMap + lambda

# Python code to merge elements of sublists
  
# Initialisation of first list
list1 = [[1, 20, 30],
         [40, 29, 72],
         [119, 123, 115]]
  
# Initialisation of second list
list2 = [[29, 57, 64, 22],
         [33, 66, 88, 15],
         [121, 100, 15, 117]]
  
# Using map + lambda to merge lists
Output = list(map(lambda x, y:x + y, list1, list2))
  
# Printing output
print(Output)
Producción:

[[1, 20, 30, 29, 57, 64, 22],
 [40, 29, 72, 33, 66, 88, 15], 
 [119, 123, 115, 121, 100, 15, 117]]

 
Método #2: UsarZip()

# Python code to merge elements of sublists
  
# Initialisation of first list
list1 = [[1, 20, 30],
         [40, 29, 72],
         [119, 123, 115]]
  
# Initialisation of second list
list2 = [[29, 57, 64, 22],
         [33, 66, 88, 15],
         [121, 100, 15, 117]]
  
# Using zip to merge lists
Output = [x + y for x, y in zip(list1, list2)]
  
# Printing output
print(Output)
Producción:

[[1, 20, 30, 29, 57, 64, 22],
 [40, 29, 72, 33, 66, 88, 15],
 [119, 123, 115, 121, 100, 15, 117]]

 
Método #3: Usar starmap() yconcat()

# Python code to merge elements of sublists
  
from operator import concat
from itertools import starmap
  
# Initialisation of first list
list1 = [[1, 20, 30],
         [40, 29, 72],
         [119, 123, 115]]
  
# Initialisation of second list
list2 = [[29, 57, 64, 22],
         [33, 66, 88, 15], 
         [121, 100, 15, 117]]
  
# Using starmap() and concat to merge list
Output = list(starmap(concat, zip(list1, list2)))
  
# Printing output
print(Output)
Producción:

[[1, 20, 30, 29, 57, 64, 22],
 [40, 29, 72, 33, 66, 88, 15],
 [119, 123, 115, 121, 100, 15, 117]]

Publicación traducida automáticamente

Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *