Dan*_*den 1 python if-statement
我必须if在一个代码中使用一堆语句.他们都是一样的,略有变化.我有什么方法可以妥协所有这些代码并使其更优雅和更短?
代码如下:
if con_name == 'coh':
coh = my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)
coh_surro = my_coherence(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)
return coh, coh_surro, freqs, freqs_surro
if con_name == 'imcoh':
imcoh = my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)
imcoh_surro = my_imcoh(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)
return imcoh, imcoh_surro, freqs, freqs_surro
if con_name == 'cohy':
cohy = my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)
cohy_surro = my_cohy(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)
return cohy, cohy_surro, freqs, freqs_surro
if con_name == 'plv':
plv = my_plv(n_freqs, Rxy, Rxy_mean)
plv_surro = my_plv(n_freqs, Rxy_s, Rxy_s_mean)
return plv, plv_surro, freqs, freqs_surro
if con_name == 'pli':
pli = my_pli(n_freqs, Rxy, Rxy_mean)
pli_surro = my_pli(n_freqs, Rxy_s, Rxy_s_mean)
return pli, pli_surro, freqs, freqs_surro
if con_name == 'wpli':
wpli = my_wpli(n_freqs, Rxy, Rxy_mean)
wpli_surro = my_wpli(n_freqs, Rxy_s, Rxy_s_mean)
return wpli, wpli_surro, freqs, freqs_surro
Run Code Online (Sandbox Code Playgroud)
我很抱歉,如果这很容易,但我尝试过并且无法找到方法.
没有反思
func, flag = {
"coh": (my_coherence, True),
"imcoh": (my_imcoh, True)
"cohy": (my_cohy, True),
"ply": (my_plv, False),
"pli": (my_pli, False),
"wpli": (my_wpli, False)
}[con_name]
args = (n_freqs, Rxy_mean, Rxx_mean, Ryy_mean) if flag else (n_freqs, Rxy, Rxy_mean)
surro_args = (n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean) if flag else (n_freqs, Rxy_s Rxy_s_mean)
val = func(*args)
surro = func(*surro_args)
return val, surro, freqs, freqs_surro
Run Code Online (Sandbox Code Playgroud)
或者这也是可能的
...
args = (Rxy_mean, Rxx_mean, Ryy_mean) if flag else (Rxy, Rxy_mean)
surro_args = (Rxy_s_mean, Rxx_s_mean, Ryy_s_mean) if flag else (Rxy_s Rxy_s_mean)
val = func(n_freqs, *args)
surro = func(n_freqs *surro_args)
...
Run Code Online (Sandbox Code Playgroud)
也许有一个很酷的名称flag来分类这些功能.请改用它.