python:更改 numpy.array 访问方法以从 1 而不是 0 开始

标签 python arrays python-2.7 numpy

我正在将一些代码从 R 移植到 python(注意:在 R 列表中从第 1 个元素开始,而不是第 0 个元素)而不是更改我访问数组的每个地方我想创建一个 numpy.array 的子类所以例如,下面的代码

    import numpy
    class array_starting_at_one(numpy.array):
        ???
    def myfunc(A):
        print A[1,1,1]
        print A[1:3,1,:]
    A = array_starting_at_one([[[1, 2, 3], [4, 5, 6]], [[11, 12, 13], [14, 15, 16]]])
    myfunc(A)

输出

    1
    [[ 1  2  3]
     [11 12 13]]

谁知道怎么填写???在上面的代码中?

最佳答案

这是我想出的解决方案:

import numpy
def adj(attr):
    if attr==None:
        return attr
    else:
        return attr-1
def adjust_slice(x):
    if isinstance(x,int):
        return x-1
    elif isinstance(x,slice):
        return slice(*[adj(attrib) for attrib in (x.start,x.stop,x.step)])
    elif isinstance(x,list):
        return slice(x[0]-1,x[-1]-1,1)
    else:
        raise Exception("Expected slice, list, or int.")
class array_starting_at_one(list):
    def __init__(self,np_array):
        self.np_array = numpy.array(np_array)
    def __getitem__(self,i):
        if isinstance(i,int):
            i=i-1
        elif isinstance(i,tuple):
            i = tuple([adjust_slice(x) for x in i])
        else:
            return array_starting_at_one(self.np_array[adjust_slice(x)])
        return self.np_array[i]
    def __setitem__(self,i,y):
        if isinstance(i,int):
            self.np_array[i-1] = y
        elif isinstance(i,tuple):
            self.np_array[tuple([adjust_slice(x) for x in i])] = y
        else:
            self.np_array[adjust_slice(x)] = y
    def __getslice__(self,i,j):
        return array_starting_at_one(self.np_array[(i-1):(j-1)])
    def __setslice__(self,i,j,y):
        self.np_array[i-1:j-1]=y
    def __repr__(self):
        print self.np_array
    def __str__(self):
        return str(self.np_array)

它能满足我的需要,但我没有花时间仔细测试它,所以请谨慎使用。

关于python:更改 numpy.array 访问方法以从 1 而不是 0 开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26222645/

相关文章:

python - 如何使用 Python Mechanize 自动添加 Google 快讯

python - Django 在之前已设置外键的同一记录中填充值

python - 将字典列表转换为列表

python 包导入模块使用 __init__.py

python - 名称错误 : name 'process_or_store' is not defined, python

python - 锚定笔记本选项卡,使其位置无法更改

php - Json添加到mysql

C# 按索引偶数升序奇数降序对数组重新排序

c# - 在可变长度数组之间复制 c#

python - 嵌套格式规范合法吗?