NumPy切片符号在字典中 [英] NumPy slice notation in a dictionary

查看:116
本文介绍了NumPy切片符号在字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在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),
片(无,2,无),
片(无,无,无),
片(无,540,无))
pre>

生成此元组的一种方便方法是使用特殊函数* 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 of slice 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 class IndexExpression that implements a special __getitem__ method.

这篇关于NumPy切片符号在字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆