Python 如何在sympy的表达式中替换多个符号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32930284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:29:51  来源:igfitidea点击:

How to substitute multiple symbols in an expression in sympy?

pythonsympy

提问by Wesley

Assigning a variable directly does not modify expressions that used the variable retroactively.

直接分配变量不会修改追溯使用该变量的表达式。

>>> from sympy import Symbol
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> f = x + y
>>> x = 0

>>> f
x + y

采纳答案by Wesley

To substitute several values:

替换多个值:

>>> from sympy import Symbol
>>> x, y = Symbol('x y')
>>> f = x + y
>>> f.subs({x:10, y: 20})
>>> f
30

回答by MSeifert

Actually sympy is designed not to substitute values until you really want to substitute them with subs(see http://docs.sympy.org/latest/tutorial/basic_operations.html)

实际上,sympy 旨在不替换值,直到您真的想替换它们subs(请参阅http://docs.sympy.org/latest/tutorial/basic_operations.html

Try

尝试

f.subs({x:0})
f.subs(x, 0) # as alternative

instead of

代替

x = 0

回答by Adrien

The command x = Symbol('x')stores Sympy's Symbol('x')into Python's variable x. The Sympy expression fthat you create afterwards does contain Symbol('x'), not the Python variable x.

该命令x = Symbol('x')将 Sympy 存储Symbol('x')到 Python 的变量中xf您之后创建的 Sympy 表达式确实包含Symbol('x'),而不是 Python 变量x

When you reassign x = 0, the Python variable xis set to zero, and is no longer related to Symbol('x'). This has no effect on the Sympy expression, which still contains Symbol('x').

当您重新分配 时x = 0,Python 变量x设置为零,并且不再与 相关Symbol('x')。这对 Sympy 表达式没有影响,它仍然包含Symbol('x').

This is best explained in this page of the Sympy documentation: http://docs.sympy.org/latest/gotchas.html#variables

这在 Sympy 文档的这一页中得到了最好的解释:http://docs.sympy.org/latest/gotchas.html#variables

What you want to do is f.subs(x,0), as said in other answers.

f.subs(x,0)正如其他答案中所说,您想要做的是。