Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
Copying sublist structure to another list of equal length in Python

Say I have one list,

list1 = ['Dog', 'Cat', 'Monkey', 'Parakeet', 'Zebra']

And another,

list2 = [[True, True], [False], [True], [False]]

(You can imagine that the second list was created with an itertools.groupby on an animal being a house pet.)

Now say I want to give the first list the same sublist structure as the second.

list3 = [['Dog', 'Cat'], ['Monkey'], ['Parakeet'], ['Zebra']]

I might do something like this:

list3 = []
lengths = [len(x) for x in list2]
count = 0
for leng in lengths:
    templist = []
    for i in range(leng):   
        templist.append(list1[count])
        count += 1
    list3.append(templist)

Which I haven't totally debugged but I think should work. My question is if there is a more pythonic or simple way to do this? This seems kind of convoluted and I have to imagine there is a more graceful way to do it (maybe in itertools which never ceases to impress me).

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can simply use next for a no-import solution:

list1 = ['Dog', 'Cat', 'Monkey', 'Parakeet', 'Zebra']
list_1 = iter(list1)
list2 = [[True, True], [False], [True], [False]]
new_list2 = [[next(list_1) for _ in i] for i in list2]

Output:

[['Dog', 'Cat'], ['Monkey'], ['Parakeet'], ['Zebra']]

However, for input n levels deep, you can use recursion:

list1 = ['Dog', 'Cat', 'Monkey', 'Parakeet', 'Zebra']
list_1 = iter(list1)
list2 = [[True, [True, False]], [False], [[True]]]
def place_data(current):
   return [next(list_1) if isinstance(i, int) else place_data(i) for i in current]

print(place_data(list2))

Output:

[['Dog', ['Cat', 'Monkey']], ['Parakeet'], [['Zebra']]]
over 4 years ago · Santiago Trujillo Denunciar

0

Make an iter of list1 and islice the necessary N elements of each list2,e g:

from itertools import islice

list1 = ['Dog', 'Cat', 'Monkey', 'Parakeet', 'Zebra']
list2 = [[True, True], [False], [True], [False]]

it = iter(list1)
list3 = [list(islice(it, len(el))) for el in list2]
# [['Dog', 'Cat'], ['Monkey'], ['Parakeet'], ['Zebra']]
over 4 years ago · Santiago Trujillo Denunciar

0

This is one way:

from itertools import accumulate

idx_acc = [0] + list(accumulate(map(len, list2)))
list1 = [list1[i:j] for i, j in zip(idx_acc, idx_acc[1:])]

# [['Dog', 'Cat'], ['Monkey'], ['Parakeet'], ['Zebra']]
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda