使用生成器代替嵌套循环

Abh*_*mar 1 python iteration generator nested-loops

我有以下嵌套循环。但在时间上效率低下。所以使用发电机会好得多。你知道怎么做吗?

x_sph[:] = [r*sin_t*cos_p for cos_p in cos_phi for sin_t in sin_theta for r in p]     
Run Code Online (Sandbox Code Playgroud)

似乎你们中的一些人认为(查看评论)在这种情况下使用生成器没有帮助。我的印象是使用生成器将避免将变量分配给内存,从而节省内存和时间。我错了吗?

Ale*_*tke 5

从你的代码片段来看,你想做一些数字化的事情并且你想快速完成。发电机在这方面没有多大帮助。但是使用numpy模块会。这样做:

import numpy
# Change your p into an array, you'll see why.
r = numpy.array(p) # If p is a list this will change it into 1 dimensional vector.
sin_theta = numpy.array(sin_theta) # Same with the rest.
cos_phi = numpy.array(cos_phi)

x_sph = r.dot(sin_theta).dot(cos_phi)
Run Code Online (Sandbox Code Playgroud)

事实上,我会numpy更早使用,这样做:

phi = numpy.array(phi) # I don't know how you calculate this but you can start here with a phi list.
theta = numpy.array(theta)

sin_theta  =numpy.sin(theta)
cos_phi = numpy.cos(phi)
Run Code Online (Sandbox Code Playgroud)

您甚至可以跳过中间环节sin_thetacos_phi作业,将所有内容放在一行中。它会很长而且很复杂,所以我会省略它,但numpy有时我会做这样的数学运算。

而且numpy速度很快,它会产生巨大的影响。至少是一个引人注目的。