Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!