【发布时间】:2021-01-26 22:37:26
【问题描述】:
第一个问题是在 StackOverflow 中提出的,因此欢迎提供有关如何更好地“提问”的提示。
这部分代码的基本目标: 一些球 (no_balls) 沿随机方向移动。
我正在尝试从 python 列表转移到 numpy 数组以获得更好的性能。这是简化的代码。
基本问题: 我的迭代器给了我 ndarray 而不是 vpy.sphere 类型的对象,因此在我正在迭代的对象上调用 sphere.pos 失败。 或者这是不可能的,因为 Numpy 是为数字而构建的?性能替代方案?
import vpython as vpy
import numpy as np
#Create and Fill numpy array with random size balls
balls = np.empty([no_ball], dtype=vpy.sphere)
with np.nditer(balls, flags=['refs_ok'], op_flags=['readwrite']) as b_it:
debug_msg(len(b_it))
for b in b_it:
b[...] = (vpy.sphere( radius=random_in_range(ball_min_r,ball_max_r),
opacity=0.8,
color=random_RGB(),
pos=vpy.vector(0,0,0),))
debug_msg('populated balls list')
#Main Loop
debug_msg('Starting Main Loop')
while True:
vpy.rate(30)
with np.nditer(balls, flags=['refs_ok'], op_flags=['readwrite']) as b_it:
#Main Loop
debug_msg('Starting Main Loop')
while True:
vpy.rate(30)
#The actual loop manipulates the position but the problem is that I can't access the position of the sphere objects. Type returns nd.array for b
for b in b_it:
debug_msg(type(b[...]))
debug_msg(b[...].pos)
#Above outputs
<class 'numpy.ndarray'>
Traceback (most recent call last):
File "path", line 93, in <module>
debug_msg(b[...].pos)
AttributeError: 'numpy.ndarray' object has no attribute 'pos'
如何调用数组中对象的方法和成员。顺便说一句,为什么我需要调用 b[...] 而不是 b,似乎已经过时了。
【问题讨论】:
-
像这样使用
numpy可能会使您的性能变差。问题,print(balls.dtype)显示什么? -
bfromnditer是一个包含vpy对象的 0d 数组。b.item().pos可能有效。但是nditer并没有提高对象 dtype 数组的迭代速度。并且使用对象 dtype 数组并不是对列表的改进。 -
正如您所建议的,numpy 实际上是关于数字的集合,如果您要存储对象的集合,numpy 就会失去许多优势。通常,我最终在将系统移动到 numpy 时所做的概念上的改变是,如果我有一个代表具有
x的 Ball 的类,它是一个浮点数,我删除 Ball 类并为 Balls 创建一个类并且具有 @ 987654331@ 这是一个包含所有球位置的 numpy 数组。这样你就可以得到大量的数字,这正是 numpy 想要的。 -
我从所有替代方案中看到,numpy 可能不是要走的路。 @tom10 我不确定我是否理解正确。您是否建议创建一个包含球列表的类,其位置引用一个填充了该数据的 numpy 数组?
-
@juanpa.arrivillaga 返回 'object' 什么是迭代和操作/调用大量对象方法的有效方法?
标签: python arrays numpy iterator vpython