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

Mau*_*ice 0 python matplotlib

我打算在python中做这样的事情:

plt.plot(xval_a_target, q_prof_target, label=r"target", color=target_color, ls=target_style, linewidth=lwidth)
Run Code Online (Sandbox Code Playgroud)

我正在以这种方式创建许多不同的图,并希望将后一部分分配给变量:

target_plot_style = """label=r"target", color=target_color, ls=target_style, linewidth=lwidth"""
Run Code Online (Sandbox Code Playgroud)

为了将绘图线缩短为: plt.plot(xval_a_target, q_prof_target, eval(target_plot_style),我尝试使用eval和exec进行了尝试,但是它不起作用。有没有简单的方法可以做到这一点?

dec*_*eze 6

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

kwargs = dict(label=r"target", color=target_color, ls=target_style, linewidth=lwidth)
Run Code Online (Sandbox Code Playgroud)

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

plt.plot(xval_a_target, q_prof_target, **kwargs)
Run Code Online (Sandbox Code Playgroud)

或者您可以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)
Run Code Online (Sandbox Code Playgroud)

或者您创建一个函数:

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)
Run Code Online (Sandbox Code Playgroud)

不要以创建源代码并eval即时对其进行思考。