Dada una Lista, realizar la suma de elementos consecutivos, por superposición.
Entrada : test_list = [4, 7, 3, 2]
Salida : [11, 10, 5, 6]
Explicación : 4 + 7 = 11, 7 + 3 = 10, 3 + 2 = 5 y 2 + 4 = 6 .Entrada : test_list = [4, 7, 3]
Salida : [11, 10, 7]
Explicación : 4+7=11, 7+3=10, 3+4=7.
Método 1: usar la lista de comprensión + zip()
En esto, comprimimos la lista, con elementos consecutivos usando zip() y luego realizamos la suma usando el operador +. La parte de la iteración se realiza utilizando la comprensión de listas.
Python3
# initializing list test_list = [4, 7, 3, 2, 9, 2, 1] # printing original list print("The original list is : " + str(test_list)) # using zip() to get pairing. # last element is joined with first for pairing res = [a + b for a, b in zip(test_list, test_list[1:] + [test_list[0]])] # printing result print("The Consecutive overlapping Summation : " + str(res))
The original list is : [4, 7, 3, 2, 9, 2, 1] The Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]
Método #2: Usando sum() + comprensión de lista + zip()
En esto, realizamos la tarea de obtener la suma usando sum() y todas las funcionalidades se mantienen de manera similar al método anterior.
Python3
# Python3 code to demonstrate working of # Consecutive overlapping Summation # Using sum() + list comprehension + zip() # initializing list test_list = [4, 7, 3, 2, 9, 2, 1] # printing original list print("The original list is : " + str(test_list)) # using sum() to compute elements sum # last element is joined with first for pairing res = [sum(sub) for sub in zip(test_list, test_list[1:] + [test_list[0]])] # printing result print("The Consecutive overlapping Summation : " + str(res))
The original list is : [4, 7, 3, 2, 9, 2, 1] The Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]
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