Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否将计算结果写入其数组?_Python_Multidimensional Array_Numpy_Scientific Computing - Fatal编程技术网

Python 是否将计算结果写入其数组?

Python 是否将计算结果写入其数组?,python,multidimensional-array,numpy,scientific-computing,Python,Multidimensional Array,Numpy,Scientific Computing,这是关于编写高效python程序的后续问题。我一直在玩弄编写自己的物理模拟,想摆脱使用十亿个类和方法 所以我希望能够对数据集执行计算。这是我的最新尝试: particles = np.array([ #position, last position, velocity, mass, size [[200,0],[200,200],[5,5],10,15], \ [[210,210],[210,210],[8,2],20,25],

这是关于编写高效python程序的后续问题。我一直在玩弄编写自己的物理模拟,想摆脱使用十亿个类和方法

所以我希望能够对数据集执行计算。这是我的最新尝试:

particles = np.array([ #position, last position, velocity, mass, size
                 [[200,0],[200,200],[5,5],10,15], \
                 [[210,210],[210,210],[8,2],20,25],\
                 [[215,215],[195,195],[5,3],5,15], \
                 [[192,186],[160,160],[10,-4],30,30]])

def moveParticles(part, dt):
    part[0] = part[1]
    part[1] += np.multiply(part[2],dt)
我试图将每个粒子的每个属性存储在一个数组中,然后在适当的位置更新它们。这里,我试着用时间步长乘以速度向量,然后把它加到位置向量上。这对我来说似乎是一种自然的表达方式,但它给了我一个错误:

TypeError: can't multiply sequence by non-int of type 'float'
我可以将数据写回同一个数组吗?我将如何进行

我一直在四处阅读,并研究了numpy的矢量化函数、itertools、map()等。。。但是我如何将结果放回原始数组中呢


或者在覆盖原始粒子之前使用中间数组来存储结果是唯一的方法吗?

我认为,您只是以错误的方式调用了例程(可能会将其传递给整个粒子数组,而不是仅传递一个粒子的数组)

无论如何,另一种可能的解决方案是将阵列拆分为单个阵列:

import numpy as np
pos = np.array([[200,0], [210,210], [215,215], [192,186]], dtype=float)
lastpos = np.array([[200,2000], [ 210,210], [195, 195], [160,160]], dtype=float)
velocity = np.array([[ 5,5], [8,2], [5,3], [10,-4]], dtype=float)
mass = np.array([ 10, 20, 5, 30 ], dtype=float)
size = np.array([ 15, 25, 15, 30 ], dtype=float)

def moveParticles(pos, lastpos, velocity, dt):
    lastpos[:] = pos[:]
    pos[:] += velocity * dt
这将对
pos
lastpos
进行就地替换。要移动粒子,必须调用以下函数:

moveParticles(pos, lastpos, velocity, 1)

其中,我将dt设置为1。我还假设您想要浮点坐标,如果不想要,则应生成整数数组。

如何调用moveParticles?请提供请求的输出。由于数据中有不同长度的列表,
np.array
返回的是dtype
object
particleles[:,0]
粒子[:,1]
粒子[:,2]
是Python列表,而不是数组。因此,当您尝试将velocity列表与
dt
浮点相乘时会出现错误。您也应该尝试将同质数据存储在数组中。我喜欢下面Balint的sanswer!这看起来确实是一个非常好的解决方案。这意味着如果我破坏了parti,我将不得不从多个数组中删除相同的元素cle,而不仅仅是删除单个元素。谢谢!