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

224
Visualizações
Use variable to indicate index range

I want to create a list containing indices that would be used to get elements from another list.

A simple case:

A = [5,6,7,8,9,10]    
b = 2:4  

I want to then do something like

C = A[b]

Which would be like saying C = A[2:4]

I want to later extend this to multidimensional arrays, where e.g b = [2:4, 5:6] and I can simply call A[b] to extract a multidimensional array out of A.

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

0

You can define b as a slice object to achieve this:

In[9]:
A = [5,6,7,8,9,10]    
b = slice(2,4)
A[b]

Out[9]: [7, 8]

Regarding your other requirement I think if you create a list object containing 2 slice objects then it should achieve what you want:

In[18]:
import numpy as np
a = np.arange(100).reshape(10,10)
b = [slice(1,3), slice(3,4)]
a[b]

Out[18]: 
array([[13],
       [23]])
over 4 years ago · Santiago Trujillo Relatório

0

You can either use straight python using e.g. slice:

>>> A = [5,6,7,8,9,10]    
>>> b = slice(2,4)
>>> A[b]
[7, 8]

But this does not scale very well to nd-arrays. To do this, I'd recommend using numpy's np.s_ function which does exactly what you are looking for, without the need of explicitly constructing a slice for each axis.

>>> b = np.s_[2:4]
>>> A[b]
[7, 8]

This extends nicely to e.g. 2d arrays:

>>> A = np.ones(10, 10)
>>> b = np.s_[2:4, 5:6]
>>> A[b]
array([[ 1.],
       [ 1.]])
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