List slicing in Python: is there something like -0?

I have a 3D array and would like to break it into many sub-selections. This is my code:

# 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), xonly matches to crop - 1, the last record in dimension x always drops out
  • If I use x in range(crop+1), xit rises up crop, leading to a fragment arr[crop:-0, ...]that has the form[0, y_dim, z_dim]

I know the usual answer, simply remove the upper limit, for example arr[crop:, :, :]. This is usually quite convenient. But how to do this in understanding the list?

+4
source share
2 answers

In such cases, it is better to avoid negative indices.

, i>0, a[-i] a[len(a)-i]. i==0.

:

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)]
+5

if..else None:

>>> 'abc'[:None if 1 else -1]
'abc'
>>> 'abc'[:None if 0 else -1]
'ab'
+2

Source: https://habr.com/ru/post/1659154/


All Articles