在python中,如何为自己的矩阵类创建两个索引切片? [英] In python, how do I create two index slicing for my own matrix class?

查看:265
本文介绍了在python中,如何为自己的矩阵类创建两个索引切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在python中编写自己的矩阵类,仅用于测试目的.实际上,这个矩阵类是用c ++编写的,我正在使用SWIG在两者之间进行接口.但是,对于这个问题,考虑此矩阵类的纯python实现可能会更简单.

I am trying to write my own matrix class in python, just for testing purposes. In reality, this matrix class is in c++ and I am using SWIG to interface between the two. However, for this question, it might be simpler to consider a pure python implementation of this matrix class.

我希望能够调用此矩阵类并使用双索引切片.例如,在我们创建一个4x4的1的矩阵后,

I want to be able to call this matrix class and use two-indexed slicing. For example, after we create 4x4 matrix of ones,

>>> A = Matrix(4,4,1)

我希望能够获得sub 2x2矩阵:

I want to be able to get the sub 2x2 matrix:

>>>> A[1:2,1:2]

我听说过__getslice__方法,但这似乎只允许单切片,例如A[1:2].那么如何执行二索引切片,以便我可以调用A[i:j,l:k]?

I've heard of the __getslice__ method, but this seems like it only allows single slicing, e.g. A[1:2]. So how can perform a two-index slicing so I can call A[i:j,l:k]?

谢谢!

推荐答案

请注意,自版本2.0起不推荐使用__getslice__.

Note that __getslice__ is deprecated since version 2.0.

因此,请考虑以下最小示例:

So consider the following minimal example:

class Foo:
    def __getitem__(self, *args):
        print args
f = Foo()
f[1:2,2:4]

这将打印:

((slice(1, 2, None), slice(2, 4, None)),)

如果您查看数据模型文档,您将看到slice对象是:

If you have a look at the data model docs, you'll see that slice objects are:

...用于表示使用扩展切片语法时的切片. 特殊的只读属性:start是下限; stop是 上限step是步长值;如果省略,则每个为None.这些 属性可以具有任何类型.

...used to represent slices when extended slice syntax is used. Special read-only attributes: start is the lower bound; stop is the upper bound; step is the step value; each is None if omitted. These attributes can have any type.

从这里应该很清楚如何实现2索引切片处理.

From here it should be pretty clear how to implement your 2 index slice handling.

这篇关于在python中,如何为自己的矩阵类创建两个索引切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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