如何将一行python代码分配给一个变量



我在python中绘图,这样做:

plt.plot(xval_a_target, q_prof_target, label=r"target", color=target_color, ls=target_style, linewidth=lwidth)

我用这种方式创建了很多不同的图,并想将后一部分分配给一个变量:

target_plot_style = """label=r"target", color=target_color, ls=target_style, linewidth=lwidth"""

为了将绘图线缩短为:plt.plot(xval_a_target, q_prof_target, eval(target_plot_style),我用eval和exec尝试过,但它不起作用。有简单的方法吗?

您可以使用dict来保存这些值:

kwargs = dict(label=r"target", color=target_color, ls=target_style, linewidth=lwidth)

然后将它们应用于函数调用:

plt.plot(xval_a_target, q_prof_target, **kwargs)

或者使用partial创建一个部分应用的函数:

from functools import partial
p = partial(plt.plot, label=r"target", color=target_color, ls=target_style, linewidth=lwidth)
p(xval_a_target, q_prof_target)

或者创建一个函数:

def p(xval_a_target, q_prof_target):
return plt.plot(xval_a_target, q_prof_target, label=r"target", color=target_color, ls=target_style, linewidth=lwidth)

不要考虑创建源代码和动态eval

因此,本质上您希望流程更加标准化。

有两种正确的方法:

  1. 保存要额外传递到dict的参数,并在调用时传递该dict:

    target_plot_style = dict(label=r"target", color=target_color,
    ls=target_style, linewidth=lwidth)
    plt.plot(xval_a_target, q_prof_target, **target_plot_style)
    
  2. 为这种类型的绘图创建包装:

    special_plot = lambda x, y: plt.plot(xval_a_target, q_prof_target, label=r"target",
    color=target_color, ls=target_style, linewidth=lwidth)
    special_plot(xval_a_target, q_prof_target)
    

    或者

    def special_plot(x, y):
    return plt.plot(xval_a_target, q_prof_target, label=r"target",
    color=target_color, ls=target_style, linewidth=lwidth)
    special_plot(xval_a_target, q_prof_target)
    

这是如何创建具有所需值的dict的示例。然后您可以添加**target_plot_stype来解压缩dict.

def plt_plot(xval_a_target, q_prof_target, label, color, ls, linewidth):
pass
if __name__ == "__main__":
target_color = target_style = lwidth = xval_a_target = q_prof_target = 'value'
target_plot_style = dict(label=r"target", color=target_color, ls=target_style, linewidth=lwidth)
plt_plot(xval_a_target, q_prof_target, **target_plot_style)

最新更新