Dada una Tupla. La tarea es convertirlo a Lista agregando la string dada después de cada elemento.
Ejemplos:
Input : test_tup = (5, 6, 7), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg', 7, 'Gfg'] Explanation : Added "Gfg" as succeeding element. Input : test_tup = (5, 6), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg'] Explanation : Added "Gfg" as succeeding element.
Método #1: Usar la comprensión de listas
En esto, construimos una tupla de cada elemento de la tupla con un elemento siguiente y luego ejecutamos un ciclo anidado para aplanar cada tupla construida utilizando la comprensión de listas.
Python3
# Python3 code to demonstrate working of # Convert tuple to List with succeeding element # Using list comprehension # initializing tuple test_tup = (5, 6, 7, 4, 9) # printing original tuple print("The original tuple is : ", test_tup) # initializing K K = "Gfg" # list comprehension for nested loop for flatten res = [ele for sub in test_tup for ele in (sub, K)] # printing result print("Converted Tuple with K : ", res)
Producción:
La tupla original es: (5, 6, 7, 4, 9)
Tupla convertida con K: [5, ‘Gfg’, 6, ‘Gfg’, 7, ‘Gfg’, 4, ‘Gfg’, 9, ‘Gfg ‘]
Método #2: Usar chain.from_iterable() + list() + generador de expresión
Esto es similar al método anterior, la diferencia es que el bucle anidado se evita aplanando usando chain.from_iterable().
Python3
# Python3 code to demonstrate working of # Convert tuple to List with succeeding element # Using chain.from_iterable() + list() + generator expression from itertools import chain # initializing tuple test_tup = (5, 6, 7, 4, 9) # printing original tuple print("The original tuple is : ", test_tup) # initializing K K = "Gfg" # list comprehension for nested loop for flatten res = list(chain.from_iterable((ele, K) for ele in test_tup)) # printing result print("Converted Tuple with K : ", res)
Producción:
La tupla original es: (5, 6, 7, 4, 9)
Tupla convertida con K: [5, ‘Gfg’, 6, ‘Gfg’, 7, ‘Gfg’, 4, ‘Gfg’, 9, ‘Gfg ‘]
Método #3: Usando los métodos list(), map(), join(), split()
Python3
# Python3 code to demonstrate working of # Convert tuple to List with succeeding element # initializing tuple test_tup = (5, 6, 7, 4, 9) # printing original tuple print("The original tuple is : ", test_tup) # initializing K K = "Gfg" x = list(map(str, test_tup)) b = "*"+K+"*" a = b.join(x) c = a.split("*") c.append(K) res = [] for i in c: if(i != K): res.append(int(i)) else: res.append(i) # printing result print("Converted Tuple with K : ", res)
Producción :
La tupla original es: (5, 6, 7, 4, 9)
Tupla convertida con K: [5, ‘Gfg’, 6, ‘Gfg’, 7, ‘Gfg’, 4, ‘Gfg’, 9, ‘Gfg ‘]
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