Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 233
lhk Avatar asked Feb 06 '23 20:02

lhk


2 Answers

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)]
like image 93
shx2 Avatar answered Feb 08 '23 08:02

shx2


Use a ternary if..else with None:

>>> 'abc'[:None if 1 else -1]
'abc'
>>> 'abc'[:None if 0 else -1]
'ab'
like image 42
TigerhawkT3 Avatar answered Feb 08 '23 08:02

TigerhawkT3