考虑我的代码
a,b,c = np.loadtxt ('test.dat', dtype='double', unpack=True)
a、b和c是相同的数组长度。你知道吗
for i in range(len(a)):
q[i] = 3*10**5*c[i]/100
x[i] = q[i]*math.sin(a)*math.cos(b)
y[i] = q[i]*math.sin(a)*math.sin(b)
z[i] = q[i]*math.cos(a)
我试图找出X、Y、Z 2点之间的差值的所有组合来迭代这个方程(席XJ)+(Y-YJ)+(Zi-ZJ)=R我用这个密码
for combinations in it.combinations(x,2):
xdist = (combinations[0] - combinations[1])
for combinations in it.combinations(y,2):
ydist = (combinations[0] - combinations[1])
for combinations in it.combinations(z,2):
zdist = (combinations[0] - combinations[1])
r = (xdist + ydist +zdist)
对于我拥有的一个大文件来说,python需要很长时间,我想知道是否有一种更快的方法来获取r的数组,最好是使用嵌套循环?你知道吗
例如
if i in range(?):
if j in range(?):
嗯,你的计算很复杂。此外,如果要将所有
r
值存储在一个列表中,则需要大量内存。通常,您不需要一个列表,一个生成器可能就足够处理这些值了。你知道吗考虑以下代码:
它返回一个生成器,每次调用生成器的
next()
方法时只计算一个值。你知道吗既然您显然在使用numpy,那么让我们实际使用numpy;它会更快。如果在使用numpy时完全避免python循环,而是使用它的矢量化数组操作,那么它几乎总是更快,而且通常更容易阅读。你知道吗
现在,后面的示例代码并没有完成您可能希望它做的事情—注意您每次都是如何说
xdist = ...
?您正在覆盖该变量,而没有对其执行任何操作。我假设你想要每对点之间的平方欧几里德距离,使矩阵dists
,其中dists[i, j]
等于第i
点和第j
点之间的距离。你知道吗简单的方法是,如果您有可用的scipy:
如果你的列表很大,不使用squareform会更节省内存,但是它是一种压缩格式,要找到特定的距离对有点困难。你知道吗
稍微难一点,如果你不能/不想使用scipy:
它基本上实现了公式(a-b)^2=a^2-2ab+b^2,但都是向量。你知道吗
很抱歉没有发布完整的解决方案,但是您应该避免嵌套对range()的调用,因为每次调用range()时,它都会创建一个新的元组。最好调用range()一次并存储结果,或者使用循环计数器。你知道吗
例如,而不是:
…你会做:
相关问题 更多 >
编程相关推荐