Python 定义函数时对变量的求值
有人能解释一下,为什么在我评估列表中的函数时,这两段python代码没有给出相同的结果: 第1区:Python 定义函数时对变量的求值,python,Python,有人能解释一下,为什么在我评估列表中的函数时,这两段python代码没有给出相同的结果: 第1区: fct_list = [] theta = [[-2.95,0.001], [-0.5,0.511], [-0.1,0.51], [-2.95,0.001]] for i in range(4): def fct(lcs): return some_func(lcs, beta=theta[i][0], sigma=theta[i][1]) fct_list.
fct_list = []
theta = [[-2.95,0.001], [-0.5,0.511], [-0.1,0.51], [-2.95,0.001]]
for i in range(4):
def fct(lcs):
return some_func(lcs, beta=theta[i][0], sigma=theta[i][1])
fct_list.append(fct)
第2区:
def fct_1(lcs):
return some_func(lcs, beta=-2.95, sigma=0.001)
def fct_2(lcs):
return some_func(lcs, beta=-0.5, sigma=0.511)
def fct_3(lcs):
return some_func(lcs, beta=-0.1, sigma=0.51)
def fct_4(lcs):
return some_func(lcs, beta=-2.95, sigma=0.001)
fct_list = [fct_1,fct_2,fct_3,fct_4]
在第一种情况下,似乎没有对参数求值,在执行函数时,它使用内存中的θ值
我希望beta和sigma的值在函数中进行硬编码,就像在第二种情况下一样,但是在构建列表时使用评估的参数值。有人知道怎么做吗
我目前的方法是将block 2写在一个单独的文件中,以便在我构建列表时对beta和sigma的数值进行硬编码。有没有更干净的方法 我想问题在于您正在每个 迭代步骤,也适用于前面的函数 在fct_列表中。。。 内置functools库实际上有一个很好的函数用于您的目的():
当您通过循环构建列表时,变量
i
是闭包,并且在内部函数fct()
中被“记住”。但是这个变量i
通过引用被记住,因此当您更改它时(通过迭代您将更改它),最终值是3
。参见示例,我在内部函数中添加了printfct
:
fct_list1 = []
fct_list2 = []
theta = [[-2.95,0.001], [-0.5,0.511], [-0.1,0.51], [-2.95,0.001]]
def some_func(l, beta, sigma):
print(l, beta, sigma)
for i in range(4):
def fct(lcs):
print(i)
return some_func(lcs, beta=theta[i][0], sigma=theta[i][1])
fct_list1.append(fct)
def fct_1(lcs):
return some_func(lcs, beta=-2.95, sigma=0.001)
def fct_2(lcs):
return some_func(lcs, beta=-0.5, sigma=0.511)
def fct_3(lcs):
return some_func(lcs, beta=-0.1, sigma=0.51)
def fct_4(lcs):
return some_func(lcs, beta=-2.95, sigma=0.001)
fct_list2 = [fct_1,fct_2,fct_3,fct_4]
for f in fct_list1:
f(theta)
print('-' * 80)
for f in fct_list2:
f(theta)
输出:
3
[[-2.95, 0.001], [-0.5, 0.511], [-0.1, 0.51], [-2.95, 0.001]] -2.95 0.001
3
[[-2.95, 0.001], [-0.5, 0.511], [-0.1, 0.51], [-2.95, 0.001]] -2.95 0.001
3
[[-2.95, 0.001], [-0.5, 0.511], [-0.1, 0.51], [-2.95, 0.001]] -2.95 0.001
3
[[-2.95, 0.001], [-0.5, 0.511], [-0.1, 0.51], [-2.95, 0.001]] -2.95 0.001
--------------------------------------------------------------------------------
[[-2.95, 0.001], [-0.5, 0.511], [-0.1, 0.51], [-2.95, 0.001]] -2.95 0.001
[[-2.95, 0.001], [-0.5, 0.511], [-0.1, 0.51], [-2.95, 0.001]] -0.5 0.511
[[-2.95, 0.001], [-0.5, 0.511], [-0.1, 0.51], [-2.95, 0.001]] -0.1 0.51
[[-2.95, 0.001], [-0.5, 0.511], [-0.1, 0.51], [-2.95, 0.001]] -2.95 0.001
解决方案之一是稍微修改循环中的代码:
for i in range(4):
def fct(lcs, index):
return some_func(lcs, beta=theta[index][0], sigma=theta[index][1])
fct_list1.append(lambda lcs, index=i: fct(lcs, index))
for i in range(4):
def fct(lcs, index):
return some_func(lcs, beta=theta[index][0], sigma=theta[index][1])
fct_list1.append(lambda lcs, index=i: fct(lcs, index))