lhk lhk - 1 month ago 12
Python Question

Slicing a list in Python: is there something like -0?

I've got a 3D array and would like to split it into many subvolumes.
This is my code so far:

# this results in a 3D array
arr = trainMasks[0, 0, :, :, :]
crop = 3
arrs = [arr[x:-(crop - x), y:-(crop - y), z:-(crop - z)]
for x in range(crop + 1)
for y in range(crop + 1)
for z in range(crop + 1)]



  • If I use
    x in range(crop)
    ,
    x
    only goes up to
    crop - 1
    , the last entry in the x dimension is always dropped

  • If I use
    x in range(crop+1)
    ,
    x
    it goes up to
    crop
    , that will result in a slice
    arr[crop:-0, ...]
    which has the shape
    [0, y_dim, z_dim]



I know the usual answer, just drop the upper limit, like this:
arr[crop:, :, :]
. Usually that's quite convenient. But how do I do that in the list comprehension ?

Answer

In cases like this it is better to avoid negative indexes.

Remeber that for i>0, a[-i] is equivalent to a[len(a)-i]. But in your case, you also need to work for i==0.

This works:

d1, d2, d3 = arr.shape
arrs = [arr[ x : d1-(crop-x), y : d2-(crop-y), z : d3-(crop-z)]
        for x in range(crop + 1)
        for y in range(crop + 1)
        for z in range(crop + 1)]
Comments