python如何设置双索引_在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.

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)

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

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

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]?

Thanks!

解决方案

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]

This will print:

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

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

...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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值