gpt4 book ai didi

python - 在 python 中使用 format(**locals()) 插入之前操作值

转载 作者:太空宇宙 更新时间:2023-11-03 18:24:45 25 4
gpt4 key购买 nike

是否可以在 .format() 中使用局部变量之前通过 **locals() 对其进行操作,而无需创建新变量?与此具有相同效果的东西:

medium="image"
size_name="double"
width=200
height=100
width2=width*2
height2=height*2
print "A {size_name} sized {medium} is {width2} by {height2}".format(**locals())

但更优雅,无需创建 width2 和 height2 变量。我试过这个:

medium="image"
size_name="double"
width=200
height=100
print "A {size_name} sized {medium} is {width2} by {height2}".format(**locals(),height2=height*2,width2=width*2)

但它在 locals() 之后的第一个逗号处抛出错误“SyntaxError: invalid syntax”。

最佳答案

只需更改顺序:

print "A {size_name} sized {medium} is {width2} by {height2}".format(height2=height*2,width2=width*2,**locals())

明星争论总是出现在普通争论之后。

为了使这个答案不再那么琐碎,这是我的标准轨道:

import string

def f(s, *args, **kwargs):
"""Kinda "variable interpolation". NB: cpython-specific!"""
frame = sys._getframe(1)
d = {}
d.update(frame.f_globals)
d.update(frame.f_locals)
d.update(kwargs)
return string.Formatter().vformat(s, args, d)

它可以像这样应用于您的示例:

 print f("A {size_name} sized {medium} is {0} by {1}", width*2, height*2)

本地(和全局)变量自动传入,表达式使用数字占位符。

关于python - 在 python 中使用 format(**locals()) 插入之前操作值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23424770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com