[英]Convert list of strings SymPy to symbols and use in solveset
The post " How can I convert a list of strings into sympy variables? " discusses how to generate SymPy symbols from a list of strings.文章“ 如何将字符串列表转换为 sympy 变量? ”讨论了如何从字符串列表生成 SymPy 符号。 My question is what steps are needed to use these symbols x, y and z in SymPy calculations?
我的问题是在 SymPy 计算中使用这些符号 x、y 和 z 需要哪些步骤?
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".但我收到错误“NameError:名称'x'未定义”。 Any help is greatly appreciated.
任何帮助是极大的赞赏。
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 from sympy.abc
( from sympy.abc import x
).您需要手动将符号存储到所需的变量中(
x = symbols('x')
),或从sympy.abc
导入它们( from sympy.abc import x
)。
The name error is happening because you haven't defined what x
, y
or z
are in your code.发生名称错误是因为您尚未定义代码中的
x
、 y
或z
。
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
:您可以使用
var
从字符串列表(或空格或逗号分隔的名称字符串)在当前命名空间中创建 Python 变量:
>>> names = 'x y z' # or 'x, y, z'
>>> var(names)
(x, y, z)
>>> var(list('xyz'))
[x, y, z]
>>> var(set('xyz'))
{x, y, z}
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.在所有情况下,发出
var
命令后,您将能够使用已分配有同名 SymPy 符号的变量。
that I have a lot of items in my list that I wish to define as symbols
我的列表中有很多我想定义为符号的项目
Just FYI, a snippet which can automatically define the symbols in an enhanced fashion仅供参考,一个片段可以以增强的方式自动定义符号
nmax = 7
names = ["phi" + str(i) for i in range(nmax)]
sympy_vars = [symbols("\\" + name.replace("phi", "phi_")) for name in names]
globals().update(dict(zip(names, sympy_vars)))
phi0
This yields a nice LaTeX type output in, eg, jupyter notebooks.这会在 jupyter notebooks 等中产生很好的 LaTeX 类型输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.