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

在Python中切片列表:是否有类似-0的东西?,python,arrays,numpy,list-comprehension,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

我有一个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)]
  • 如果我在范围(裁剪)中使用
    x
    x
    仅上升到
    crop-1
    ,则始终会删除x维度中的最后一个条目
  • 如果我在范围(裁剪+1)中使用
    x
    x
    它将上升到
    crop
    ,这将产生一个切片
    arr[crop:-0,…]
    ,其形状为
    [0,y\u dim,z\u dim]

我知道通常的答案,只要降低上限,就像这样:
arr[crop:,:,:]
。通常这很方便。但是我如何在列表理解中做到这一点呢?

使用三元
if..else
None

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

在这种情况下,最好避免使用负索引

请记住,对于
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)]

非常有趣。我不知道没有一个可以作为索引。我会接受另一个答案,因为它稍微干净了一点,但非常感谢您的见解,这是如此简单!我不知道您可以使用
None
作为
list[None:None]
。我认为它仅限于整数。是的,有负零和正零>>>np.NZERO-0.0>>>np.PZERO 0.0>>>np.NZERO>>np.NZERO==np.PZERO True这类东西并不完全符合您的期望,但在表示数字时很有用。还有南安无限变型