Is there an efficient way to access multiple slices of an array with a flexible number of slices ? Example below with a for loop I would like to avoid, left and right arrays lenghts are variable...
a = np.array([0,1,2,3,4,5,6,7,8,9])
left =np.array([0,5])
right = np.array([2,8])
for i in range(len(left)):
a[left[i]:right[i]] = -1
array([0, 1, 5, 6, 7]), you can get by with just one indexing operation. But creating that array will be as expensive iterating on the slices. Unless the slice lengths all match.np.r_[tuple([slice(i,j) for i,j in zip(left,right)])]producesarray([0, 1, 5, 6, 7]). It expands the slices into arange arrays and concatenates them. It's proposed more for convenience than speed.