将字符串列表 SymPy 转换为符号并在求解集中使用
帖子“如何转换列表字符串转换为 sympy 变量?”讨论了如何从字符串列表生成 SymPy 符号。我的问题是在 SymPy 计算中使用这些符号 x、y 和 z 需要什么步骤?
我尝试了一些方法
from sympy import symbols, solveset
var_as_strings = ['x', 'y', 'z']
var_as_symbol_objects = [sympy.symbols(v) for v in var_as_strings]
var_as_symbol_objects
for x1, x2 in zip(var_as_symbol_objects, var_as_strings):
x1 = symbols(x2)
soln = solveset(x-y-z, x)
,但收到错误“NameError:名称'x'未定义”。非常感谢任何帮助。
The post "How can I convert a list of strings into sympy variables?" discusses how to generate SymPy symbols from a list of strings. My question is what steps are needed to use these symbols x, y and z in SymPy calculations?
I tried something along the lines
from sympy import symbols, solveset
var_as_strings = ['x', 'y', 'z']
var_as_symbol_objects = [sympy.symbols(v) for v in var_as_strings]
var_as_symbol_objects
for x1, x2 in zip(var_as_symbol_objects, var_as_strings):
x1 = symbols(x2)
soln = solveset(x-y-z, x)
but I get the error "NameError: name 'x' is not defined". Any help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
文档中第一个列出的陷阱回答了这个问题。
您需要手动将符号存储到所需的变量中 (
x =symbols('x')
),或从sympy.abc
导入它们(from sympy.abc)。 abc 导入 x
)。发生名称错误是因为您尚未定义代码中的
x
、y
或z
。This is answered by the first listed gotcha in the documentation.
You need to store your symbols into the required variables manually (
x = symbols('x')
), or import them fromsympy.abc
(from sympy.abc import x
).The name error is happening because you haven't defined what
x
,y
orz
are in your code.您可以使用
var
从字符串列表(或由空格或逗号分隔的名称组成的字符串)在当前命名空间中创建 Python 变量:在所有情况下,在发出
var
后命令,您将能够使用已分配具有相同名称的 SymPy 符号的变量。You can create Python variables in the current namespace from a list of strings (or a string of space or comma separated names) with
var
:In all cases, after issuing the
var
command you will be able to use variables that have been assigned SymPy symbols with the same name.仅供参考,一个可以以增强方式自动定义符号的片段
这会产生一个很好的 LaTeX 类型输出,例如, Jupyter 笔记本。
Just FYI, a snippet which can automatically define the symbols in an enhanced fashion
This yields a nice LaTeX type output in, e.g., jupyter notebooks.