【问题标题】:python: change numpy.array access method to start at 1 instead of 0python:将 numpy.array 访问方法更改为从 1 而不是 0 开始
【发布时间】:2014-12-01 02:11:37
【问题描述】:

我正在将一些代码从 R 移植到 python(注意:在 R 列表中,从第一个元素开始,而不是第 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]]

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

【问题讨论】:

  • 您可以在您的子类中覆盖__getitem__
  • 您可能可以这样做,但我建议您不要这样做。 1)它可能会涉及比您想要的更多的视图投射。 2)从长远来看,这可能比仅仅在你的脑海中保持两种语言的索引约定更令人困惑——特别是如果你计划与经常使用 numpy 的其他人一起工作。 (注意,我来自 Fortran 背景,索引也从 1 开始,并且在很短的时间之后,差异没什么大不了的......)
  • P.S.我知道 R 将 1:3 解释为 [1,2,3] 而不是 [1,2] (就像 python 所做的那样),但我有点愚蠢地向前冲,已经以艰苦的方式转换了所有这些范围。

标签: python arrays python-2.7 numpy


【解决方案1】:

这是我想出的解决方案:

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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    相关资源
    最近更新 更多