【问题标题】:What is the best way to create an object from each element in a python (numpy) array?从 python(numpy)数组中的每个元素创建对象的最佳方法是什么?
【发布时间】:2022-07-07 23:25:52
【问题描述】:

我有一个数字数组:

num_arr = np.array([1,2,3,4,5,6,7])

我需要将每个数字转换成一个对象:

class MyObj:
    def __init__(self, x):
        self.val = x

最好的方法是什么?有没有办法不使用循环来做到这一点?

【问题讨论】:

  • 您需要为数组中的每个i 使用MyObj(i),就像它是一个列表一样。您想使用 MyObj 6 次来创建 6 个实例。所以需要某种循环。

标签: python python-3.x numpy oop numpy-ndarray


【解决方案1】:

要映射到一个 numpy 数组,有 np.vectorize

class MyObj:
    def __init__(self, x):
        self.val = x

num_arr = np.array([1,2,3,4,5,6,7])
vfunc = np.vectorize(MyObj)
result = vfunc(num_arr)

【讨论】:

  • np.vectorize 有什么改进吗?速度、便利性等?
猜你喜欢
  • 1970-01-01
  • 2016-02-16
  • 2016-09-30
  • 2020-05-28
  • 1970-01-01
  • 2011-04-09
  • 1970-01-01
  • 2019-02-20
  • 2021-09-09
相关资源
最近更新 更多