【发布时间】:2018-03-03 04:14:29
【问题描述】:
我理解为什么“标准”类型的 numpy 数组几乎总是比包含相同类型数据的列表更有效。因此,最好养成使用 numpy 数组来处理简单内容的习惯,是吗?
但是,与使用列表相比,我想知道使用 numpy 数组“存储”自定义类实例的优点和缺点。
考虑
import numpy as np
class Foo:
def __init__(self, name):
self.name = name
class Bar:
def __init__(self, name):
self.name = name
self.myFoos = np.zeros(0, dtype = Foo)
def add_foo(self, some_foo):
self.myFoos = np.append(self.myFoos, some_foo)
我可以使用
self.myFoos = []
做这个决定时我应该记住什么?
Foo 类的复杂性有很大的不同吗? (在我的用例中,它可能包含 20 或 30 个标准类型,一或两个固定大小的整数数组,然后是大约 10 个简单方法。)
myFoos 中的 Foos 数量通常会产生影响吗? (在我的用例中,它将是 0 到 10)
处理 myFoos 的次数有影响吗? (在我的实际用例中,它可能会在用户操作之间被调用 10 到 20 次。)
附:虽然代码运行良好,但 pyCharm 不喜欢最后的 append 语句,它警告我
Expected type 'Union[ndarray, iterable]' got 'Foo' instead.
提前致谢!
【问题讨论】:
-
dtype=Foo并没有按照你的想法去做。 -
...it is better to get into the habit of using numpy arrays for the simple stuff,..。除非我正在做一些非常适合 numpy 的计算,否则我通常从标准库容器开始,除非我遇到性能问题然后尝试找到更好的东西。
标签: python arrays list class numpy