Estoy tratando de dividir una lista de listas, cada una con n elementos, en una lista del doble de listas, cada una con n / 2 elementos.
E.g.
list_x = [[list_a], [list_b]]
list_a = ['1','2','3','4','5','6']
list_b = ['7','8','9','10','11','12']
Requiero:
list_x2 = [[list_a2], [list_b2], [list_c2], [list_d2]]
Dónde:
list_a2 = ['1','2','3']
list_b2 = ['4','5','6']
list_c2 = ['7','8','9']
list_d2 = ['10','11','12']
Yo he tratado: Todas las posibilidades para dividir una lista en dos listas - pero agradecería conocer cómo extender algunas de las soluciones mencionadas al escenario 'listas con una lista' .
Cualquier ayuda apreciada.
4 respuestas
Nadie ofreció una solución numpy
... Puede que no sea lo que se pide, pero es bueno;)
list_a = ['1','2','3','4','5','6']
list_b = ['7','8','9','10','11','12']
list_x = [list_a, list_b]
a = np.array(list_x)
w, h = a.shape
a.shape = w*2, h//2
list_x2 = a.tolist()
Puede utilizar la comprensión de lista:
list_x = [['1', '2', '3', '4', '5', '6'], ['7', '8', '9', '10', '11', '12']]
n = 2
list_x2 = [l[i: i + len(l) // n] for l in list_x for i in range(0, len(l), len(l) // n)]
Pruebe esto :
list_x = [list_a, list_b]
#[['1', '2', '3', '4', '5', '6'], ['7', '8', '9', '10', '11', '12']]
n = 3
list_x2 = [[l[3*i:3*j+3] for i,j in zip(range(len(l)//n), range(len(l)//n))] for l in list_x]
Salida :
[[['1', '2', '3'], ['4', '5', '6']], [['7', '8', '9'], ['10', '11', '12']]]
from operator import add
from functools import reduce
addlists = lambda l: reduce(add, l)
list_a = ['1','2','3','4','5','6']
list_b = ['7','8','9','10','11','12']
list_x = [list_a, list_b]
k = len(list_a) // len(list_x)
joined = addlists(list_x)
res = list(map(list, zip(*([iter(joined)]*k))))
Preguntas relacionadas
Preguntas vinculadas
Nuevas preguntas
python
Python es un lenguaje de programación multipropósito, de tipificación dinámica y de múltiples paradigmas. Está diseñado para ser rápido de aprender, comprender y usar, y hacer cumplir una sintaxis limpia y uniforme. Tenga en cuenta que Python 2 está oficialmente fuera de soporte a partir del 01-01-2020. Aún así, para preguntas de Python específicas de la versión, agregue la etiqueta [python-2.7] o [python-3.x]. Cuando utilice una variante de Python (por ejemplo, Jython, PyPy) o una biblioteca (por ejemplo, Pandas y NumPy), inclúyala en las etiquetas.