gpt4 book ai didi

python - 在 numpy 数组中从末尾切片可变距离的更多 Pythonic 方法

转载 作者:行者123 更新时间:2023-12-01 09:24:50 24 4
gpt4 key购买 nike

我想知道是否有更好的方法从末尾编写数组裁剪/切片,但是以编程方式。这意味着,裁剪尺寸实际上可以为 0,并且我有多个维度,例如5D 张量。

这是一个简单的 2D 示例:

# This is just to have some dummy data
import numpy as np
A = np.random.rand( 10,5)

# The easy standard case:
ix = 1
iy = 1
B = A [ ix:-ix , iy:-iy] # This works

# Now the trickier case, where I'm looking for a pythonic way of doing it.
iy = 0
# Using the code from above, does not what I want => 2nd dim ==0
C1 = A [ ix:-ix , iy:-iy]

# The next line gives the result that I want but hard coded
C2 = A [ ix:-ix , : ]

# The next line also gives me what I want, but gets completely unreadable
# for real variable names and multiple dimensions
C3 = A [ ix:A.shape[0]-ix : iy:A.shape[1]-iy]


# Is there something like this in numpy, similar to Matlab?
C4 = A [ ix:end-ix , iy:end-iy ]
C5 = A [ ix:np.end-ix , iy : np.end-iy ]

我知道它对于 2D 来说看起来并没有那么糟糕,但是如果你有多个维度和真实的变量名称,代码很容易就会困惑。那么,Python 中是否有来自 Matlab 的“end”之类的东西,或者其他更 Pythonic 的方式?

最佳答案

您应该使用slice(None)。为了便于阅读,您可以将其包装在一个简单的函数中:

def s(k):
return slice(None) if k==0 else slice(k, -k)

C1 = A [ s(ix) , s(iy) ]

关于python - 在 numpy 数组中从末尾切片可变距离的更多 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50514097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com