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

172
Visualizações
Slicing Python List with inconsistent intervals

I have a list of stock prices of a company. Now I want to split the list with multiple intervals. we will store the price like: The first 2 elements, then next 3 elements, then 2 elements, and so on.

meta_stocks = [10, 9, 11, 15, 19, 22, 25, 11, 15, 17]

Output

meta_stocks = [[10, 9],[11, 15, 19],[22, 25],[ 11, 15, 17]]

I am able to split the list with 5 items each but not able to split it further

>>> [meta_stocks[i:i+interval2] for i in range(0, len(meta_stocks), interval2)]
>>> [[10, 9, 11, 15, 19], [22, 25, 11, 15, 17]]
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can use a list comprehension with the help of itertools.cycle:

meta_stocks = [10, 9, 11, 15, 19, 22, 25, 11, 15, 17]

from itertools import cycle

start = 0
l = [2,3]
c = cycle(l)

[meta_stocks[start:(start:=start+next(c))]
 for i in range(len(l)*len(meta_stocks)//sum(l))]

Output:

[[10, 9], [11, 15, 19], [22, 25], [11, 15, 17]]
over 4 years ago · Santiago Trujillo Relatório

0

You could do it like this without the aid of additional imports:

meta_stocks = [10, 9, 11, 15, 19, 22, 25, 11, 15, 17]
meta_stocks_out = []
offset = 0
interval = 2
while offset + interval <= len(meta_stocks):
    meta_stocks_out.append(meta_stocks[offset:offset+interval])
    offset += interval
    interval = 2 if interval == 3 else 3
print(meta_stocks_out)
over 4 years ago · Santiago Trujillo Relatório

0

Some itertools to the rescue:

from itertools import islice, cycle, takewhile

i = iter(meta_stocks)
intervals = [2, 3]

[*takewhile(lambda _: _, ([*islice(i, n)] for n in cycle(intervals)))]
# [[10, 9], [11, 15, 19], [22, 25], [11, 15, 17]]
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