NumPy切片符号在字典中 [英] NumPy slice notation in a dictionary
问题描述
我想知道是否可以在python字典中存储numpy slice符号。如下:
lookup = {0:[:540],
30:[540:1080],
60:[1080:]}
可以使用本机python slice语法,例如 slice(0,10,2)
,但是我没有能够存储更复杂的片段。例如,多维的 [:,:2,...,... 540]
我目前的工作周围是将值作为元组存储,然后将其解压缩到必要的片段中。
在Python 2.x中使用
语法 [:, 2,:,:540]
变成一个元组 slice
对象通过Python:
(slice(None,None,None),
pre>
片(无,2,无),
片(无,无,无),
片(无,540,无))
生成此元组的一种方便方法是使用特殊函数*
np.s _
。您只需要传递[...]
表达式。例如:>>> np.s _ [:540]
slice(无,540,无)
>>> np.s_ [:, 2,...:540]
(slice(None,None,None),
slice(无,2,无),
slice(无,无,无),
片(无,540,无))
然后,您的字典切片可以写成:
lookup = {0:np.s _ [:540],
30:np .s_ [540:1080],
60:np.s_ [1080:]}
* 技术上
s _
是类IndexExpression
实现了一个特殊的__ getitem __
。I wonder if it is possible to store numpy slice notation in a python dictionary. Something like:
lookup = {0:[:540], 30:[540:1080], 60:[1080:]}
It is possible to use native python slice syntax, e.g.
slice(0,10,2)
, but I have not been able to store more complex slices. For example, something that is multidimensional[:,:2,:, :540]
.My current work around is to store the values as tuples and then unpack these into the necessary slices.
Working in Python 2.x.
解决方案The syntax
[:, :2, :, :540]
is turned into a tuple ofslice
objects by Python:(slice(None, None, None), slice(None, 2, None), slice(None, None, None), slice(None, 540, None))
A convenient way to generate this tuple is to use the special function*
np.s_
. You just need to pass it the[...]
expression. For example:>>> np.s_[:540] slice(None, 540, None) >>> np.s_[:, :2, :, :540] (slice(None, None, None), slice(None, 2, None), slice(None, None, None), slice(None, 540, None))
Then your dictionary of slices could be written as:
lookup = {0: np.s_[:540], 30: np.s_[540:1080], 60: np.s_[1080:]}
* technically
s_
is an alias for the classIndexExpression
that implements a special__getitem__
method.这篇关于NumPy切片符号在字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!