我正在尝试从函数内部访问变量,它给了我一个错误,提示:
NameError: name 'perm_sample_1' is not defined
代码在这里:
def permutation_sample(data1,data2):
data = np.concatenate((data1,data2))
permuted_data = np.random.permutation(data)
perm_sample_1 = permuted_data[:len(data1)]
perm_sample_2 = permuted_data[len(data1):]
return perm_sample_1 , perm_sample_2
#return perm_sample_1.shape ,perm_sample_2.shape
def draw_perm_reps_func_diff(data1,data2,func,size=1):
perm_replicates = np.empty(size)
for i in range(size):
perm_sample_1 , perm_sample_2 = permutation_sample(data1,data2)
perm_replicates[i] = func(perm_sample_1) - func(perm_sample_2)
return perm_replicates
stats.ttest_ind_from_stats(mean1=np.mean(perm_sample_1), std1=np.std(perm_sample_1), nobs1=len(perm_sample_1),mean2=np.mean(perm_sample_2), std2=np.std(perm_sample_2), nobs2=len(perm_sample_2))
我假设错误在最后一行抛出(请在将来提供有意义的堆栈跟踪):
变量perm_sample_1
超出了函数调用的范围。您必须在函数之外定义它才能访问它。
一种方法是在draw_perm_reps_func_diff(...)
之外的其他值上返回它。尽管,对此有更漂亮的解决方案。
我要做的就是运行在函数外部调用变量的函数
def func(a,b):
c = a+b
d = b+5
return c , d
z , y = func(12,5)
e = z*2
f = y/5
我应该e = 34f = 2