python 为什么在公式中没有定义键的符号

wbrvyc0a  于 2023-06-28  发布在  Python
关注(0)|答案(2)|浏览(83)

我试着把字典的键定义为符号,然后用这些键做一个表达式。但是在def中,总是存在所述密钥的符号未被定义的显示错误。但是我调试了一下,它说那些键的符号已经在那里了。

import sympy as sm

def try_sym(dic):
    for k, v in dic.items():
        exec(k+"=sm.Symbol(k)")

    f = sm.Symbol("f")
    #a=sm.Symbol("a")
    f = a+b
    return f

dic = {"a":1, "b":10}

f =sm.Symbol("f")
f=try_sym(dic)
print(f)
busg9geu

busg9geu1#

你可以坚持一条当地的法令:

In [66]: def try_sym(dic):
    ...:     dd = {k:Symbol(k) for k in dic}
    ...:     f = sum(v for v in dd.values())
    ...:     return f
    ...: 

In [67]: try_sym(dic)
Out[67]: a + b

通常不鼓励使用exec以及“动态”创建局部和全局变量。虽然可能,但Python并不容易做到。

jobtbby3

jobtbby32#

import numpy as np
import sympy as sm

def try_sym(dic):
    for k, v in dic.items():
        exec(k+"=sm.Symbol(k)")

    f = sm.Symbol("f")
    #a=sm.Symbol("a")
    f = a+b
    return f

dic = {"a":1, "b":10}

f =sm.Symbol("f")
f=try_sym(dic)
print(f)

相关问题