Dada una lista de números, la tarea es crear una nueva lista a partir de la lista inicial con la condición de agregar cada elemento impar dos veces.
A continuación se presentan algunas formas de lograr la tarea anterior.
Método #1: Usar la comprensión de listas
# Python code to create a new list from initial list # with condition to append every odd element twice. # List initialization Input = [1, 2, 3, 8, 9, 11] # Using list comprehension Output = [elem for x in Input for elem in (x, )*(x % 2 + 1)] # printing print("Initial list is:'", Input) print("New list is:", Output)
Producción:
Initial list is:' [1, 2, 3, 8, 9, 11] New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]
Método #2: Usando itertools
# Python code to create a new list from initial list # with condition to append every odd element twice. # Importing from itertools import chain # List initialization Input = [1, 2, 3, 8, 9, 11] # Using list comprehension and chain Output = list(chain.from_iterable([i] if i % 2 == 0 else [i]*2 for i in Input)) # printing print("Initial list is:'", Input) print("New list is:", Output)
Producción:
Initial list is:' [1, 2, 3, 8, 9, 11] New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]
Método #3: Usar array Numpy
# Python code to create a new list from initial list # with condition to append every odd element twice. # Importing import numpy as np # List initialization Input = [1, 2, 3, 8, 9, 11] Output = [] # Using Numpy repeat for x in Input: (Output.extend(np.repeat(x, 2, axis = 0)) if x % 2 == 1 else Output.append(x)) # printing print("Initial list is:'", Input) print("New list is:", Output)
Producción:
Initial list is:' [1, 2, 3, 8, 9, 11] New list is: [1, 1, 2, 3, 3, 8, 9, 9, 11, 11]
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA