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

223
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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