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

301
Visualizações
How to make a list comprehension in python with unequal sublists

I have a list of unequal lists. I would like to generate a new list with list comprehension from the sublists.

s = [['a','b','c','d'],['e','f','g'],['h','i'],['j','k','l','m']]

I am trying the following code but it keeps raising an indexError:

new_s = []
for i in range(len(s)):
    new_s.append((i,[t[i] for t in s if t[i]))

The expected output would be:

new_s = [(0,['a','e','h','j']),(1,['b','f','i','k']),(2,['c','g','l']),(3,['d','m'])]

Any ideas how to get this to work?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can use itertools.zip_longest to iterate over each sublist elementwise, while using None as the fill value for the shorter sublists.

Then use filter to remove the None values that were used from padding.

So all together in a list comprehension:

>>> from itertools import zip_longest
>>> [(i, list(filter(None, j))) for i, j in enumerate(zip_longest(*s))]
[(0, ['a', 'e', 'h', 'j']), (1, ['b', 'f', 'i', 'k']), (2, ['c', 'g', 'l']), (3, ['d', 'm'])]
over 4 years ago · Santiago Trujillo Relatório

0

one without itertools but modifying the original list.

def until_depleted():
   while any(sl for sl in s):
    yield 1

list(enumerate(list(s_l.pop(0) for s_l in s if s_l) for _ in until_depleted()))

one without modifying the original but with a counter

idx = 0
max_idx = max(len(_) for _ in s)

def until_maxidx():
    global idx
    while idx < max_idx:
        yield 1
        idx += 1

list(enumerate(list(s_l[idx] for s_l in s if idx < len(s_l)) for _ in until_maxidx()))

A more explicit one without the inner comprehension nor calling generators:

ret = []
idx = 0
max_idx = max(len(_) for _ in s)
while idx < max_idx:
    ret.append(list(s_l[idx] for s_l in s if idx < len(s_l)))
    idx += 1

print(list(enumerate(ret)))
over 4 years ago · Santiago Trujillo Relatório

0

This is without itertools, but also without a comprehension, so I don't know if it does count as a solution.

s = [['a','b','c','d'],['e','f','g'],['h','i'],'j','k','l','m']]

new_s = []
for i in range(len(s)):
    tmp = []
    for item in s:
        tmp.extend(item[i:i+1])
    new_s.append((i, tmp))
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