在Python中切片列表:有类似-0的东西吗?

lhk*_*lhk 4 python arrays numpy list-comprehension

我有一个3D阵列,并希望将其分成许多子卷.到目前为止这是我的代码:

# 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)]
Run Code Online (Sandbox Code Playgroud)
  • 如果我使用x in range(crop),x只有最多crop - 1,x维度中的最后一个条目总是被删除
  • 如果我使用x in range(crop+1),x它会上升crop,这将产生arr[crop:-0, ...]具有形状的切片[0, y_dim, z_dim]

我知道通常的答案,只是放弃上限,如下:arr[crop:, :, :].通常这很方便.但是我如何在列表理解中做到这一点?

shx*_*hx2 5

在这种情况下,最好避免负面指数.

Remeber,对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)]
Run Code Online (Sandbox Code Playgroud)