python - 使用 for 循环在 Python 中定义多个函数?
问题描述
我需要创建 8 个看起来像 的函数fcXX_at_this_z(r)
,XX
范围从47
到54
1 的整数步长。
所以第一个函数应该有它的原型:def fc47_at_this_z(r):
,第二个函数应该有它的原型def fc48_at_this_z(r):
……最后一个函数应该有它的原型def fc54_at_this_z(r):
。
这些函数的主体应为:
return upgrade_interpolator_cXX(r)
其中 XX 的范围又是 47 到 54。
所以我需要能够在函数体中为每个函数使用函数名。
如何在 Python 中使用 for 循环定义这些函数及其主体?
此外,在我定义它们之后,我将需要使用这些函数,如下所示:
use_it(fc54_at_this_z, ...)
或者
use_it(fc47_at_this_z, ...)
所以我再次需要能够以某种方式将索引 47, 48, ..., 54 插入到该函数调用use_it(f)
中。
这将是我关于这些函数的第二个问题,在我使用 for 循环定义它们之后,如何以上述方式使用它们?理想情况下,我需要在 for 循环中使用这些,即伪代码:
for idx in range(7):
use_it(fc+(47+idx)+_at_this_z)
更大的图景
大图如下:
我需要在 z 和 r 上执行 2Dim 积分。r 极限是 z 的函数。所以它不是正方形,也不是矩形,它是 2Dims 中的一个奇怪形状,我需要整合它。我使用 N_z 将 z 分区为:
N_z = 10**3
z_is = (-zrange) + (np.arange(N_z) + 0.5) * (2.*zrange/N_z) # shall be shape(N_z,)
z
并在from的每个值处执行自适应高斯积分z_is
。我将结果存储在矩阵形状的(N_z, 8)
.
z
from的每个值的积分z_is
如下:
results = np.zeros((N_z, 8))
errs = np.zeros((N_z,8))
for i in range(N_z):
# ideally a for loop with index idx shall appear here!
# that idx dictates which fcXX we work with. I need to work with all of them, so I need this additional for-loop to integrate all the fc_XX's across r, and store results in the matrices `results, err`
# now this code doesn't work, in particular the integrate_adaptive() below cannot populate the columns of the results and errs matrices!
# it doesn't know understand the 2nd dimension of the results matrices, it just integrates f_c54, rather than all the f_cXX's!
def fc54_at_this_z(r): # depenedent only on r
I_to_query_at = get_I_at_this_z_and_r(z_is[i], r)
return (2 * pi * r * interpolator_c54(I_to_query_at))
r_thresh_of_z = get_r_thr(z_is[i])
results[i, idx], errs[i, idx] = quadpy.c1.integrate_adaptive(fc54_at_this_z, [0., r_thresh_of_z ])
解决方案
这是使用模板的可能解决方案:
fc_template = 'def fc{0}_at_this_z(r): return upgrade_interpolator_c{0}(r)'
for i in range(47, 55):
exec(f_template.format(i))
您可以定义适合您需要的不同模板,具体取决于您要执行的操作。正如其他用户在评论中指出的那样,动态创建命名函数不一定是一个好主意,所以要小心。
如果您需要在多行上定义的函数,您可以这样做:
fc_template = """
def fc{0}_at_this_z(r):
return upgrade_interpolator_c{0}(r)
"""
推荐阅读
- javascript - JavaScript 仅在函数已运行一次后才有效
- android - 从在线数据库填充列表视图
- c - 结构中的枚举
- sdl-2 - SDL2_Mixer:静态链接的音频库不需要 Mix_Init?
- vb.net - Magtek 密码键盘 BDK
- php - 基本 php - 如何使用多个函数?
- php - 如何将列从一个表数据复制到另一个表并在mysql中同时插入更多列?
- selenium-webdriver - 并行执行多个类的 testNg 执行中的不稳定行为:SeleniumWebdriver +TestNG
- python - 如何在 Python 中将两个向量合二为一?
- c# - C# 函数调用不同的方法