Dada una tupla, la tarea es dividirla en grupos más pequeños de n. Analicemos algunos métodos para realizar una tarea determinada.
Método n. ° 1: usar la función enumerar y rango
# Python code to demonstrate # how to split tuple # into the group of k-tuples # initialising tuple ini_tuple = (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10) # printing initial tuple print ("initial list", str(ini_tuple)) # code to group # tuple into size 4 tuples res = tuple(ini_tuple[x:x + 4] for x in range(0, len(ini_tuple), 4)) # printing result print ("resultant tuples", str(res))
Producción:
lista inicial (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10)
tuplas resultantes ((1, 2, 3, 4), (8 , 12, 3, 34), (67, 45, 1, 1), (43, 65, 9, 10))
Método n.° 2: Usar el operador enumerar y modificar
# Python code to demonstrate # how to split tuple # into the group of k-tuples # initialising tuple ini_tuple = (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10) # printing initial tuple print ("initial list", str(ini_tuple)) # code to group # tuple into size 4 tuples res = tuple(ini_tuple[n:n + 4] for n, i in enumerate(ini_tuple) if n % 4 == 0) # printing result print ("resultant tuples", str(res))
Producción:
lista inicial (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10)
tuplas resultantes ((1, 2, 3, 4), (8 , 12, 3, 34), (67, 45, 1, 1), (43, 65, 9, 10))
Método #3: Usar recetas de itertools
# Python code to demonstrate # how to split tuple # into the group of k-tuples # function to group tuple into groups of 4 def grouper(n, iterable): args = [iter(iterable)] * n return zip(*args) # initialising tuple ini_tuple = (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10) # printing initial tuple print ("initial list", str(ini_tuple)) # code to group # tuple into size 4 tuples res = tuple(grouper(4, ini_tuple)) # printing result print ("resultant tuples", str(res))
Producción:
lista inicial (1, 2, 3, 4, 8, 12, 3, 34, 67, 45, 1, 1, 43, 65, 9, 10)
tuplas resultantes ((1, 2, 3, 4), (8 , 12, 3, 34), (67, 45, 1, 1), (43, 65, 9, 10))
Publicación traducida automáticamente
Artículo escrito por garg_ak0109 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA