Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda