如何将一行python代码分配给变量
我正在用python绘图,做如下工作:如何将一行python代码分配给变量,python,matplotlib,Python,Matplotlib,我正在用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, linewid
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\u a\u target,q\u prof\u target,eval(target\u plot\u 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)
或用于创建部分应用的函数:
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)
或者创建一个函数:
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)
不要考虑创建源代码和动态评估源代码。因此,基本上您希望流程更加标准化 有两种适当的方法可以做到这一点:
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)
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\u plot\u 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)
您可以使用dict和嵌套列表这样工作。
“
将被视为字符串。您不能使用这样的变量:))第一个建议是使用字典扩展(**在字典前面),这是最简单和最具python风格的方法。@Syntaxén视情况而定。如果您想将此函数传递给其他代码,而不需要它担心kwargs
,那么其他两个更好。