numpy记录的成员函数

2024-09-29 19:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须使用numpy记录数组来保存RAM和快速访问。但我想在这些记录上使用成员函数。例如

X=ones(3, dtype=dtype([('foo', int), ('bar', float)]))
X[1].incrementFooBar()

对于普通的python类,我可以

class QQQ:
  ...
  def incrementFooBar(self):
    self.foo+=1
    self.bar+=1
pass
X=[QQQ(),QQQ(),QQQ()]
X[1].incrementFooBar()

我怎么能做这样的事,但要不是为了numpy唱片?你知道吗


Tags: 函数selfnumpyfoo记录onesbar成员
1条回答
网友
1楼 · 发布于 2024-09-29 19:34:10

我可能错了,但我不认为有一种方法可以像那样对numy数组中的记录使用成员函数。或者,您可以非常轻松地构造一个函数来完成相同的任务:

X=ones(3, dtype=dtype([('foo', int), ('bar', float)]))

def incrementFooBar(X, index):
    X['foo'][index] += 1
    X['bar'][index] += 1

#then instead of "X[1].incrementFooBar()"
incrementFooBar(X, 1)

相关问题 更多 >

    热门问题