问题描述
我有以下问题:
x=Symbol('x')
book={1:2*x,2:3*x}
x=2
print(book) >>> {1:2*x,2:3*x}
我曾希望它会打印 {1:4,2:6}
但是如果我设置 book={1:2*x,2:3*x}
就在打印语句之前,我得到了想要的结果.
But if I set book={1:2*x,2:3*x}
just before the print statement, I get the wanted result.
令人沮丧的是,如果我改为编写 book=book
,这应该是相同的(对吗?),就在打印语句之前,我得到 {1:2*x,2:3*x}
- 为什么会这样?
The frustrating thing is, if I instead write book=book
, which should be the same (right?), just before the print statement, I get {1:2*x,2:3*x}
- why is that?
推荐答案
您正在处理 x
的两个不同值,因为您正在讨论将 x
设置为在一种情况下不是 Symbol('x')
而不是另一种情况.一种情况:
You're dealing with two different values of x
because you're talking about setting x
to something other than Symbol('x')
in one case but not the other. In one case:
x=Symbol('x')
book={1:2*x,2:3*x}
x=2
print(book)
结果:
{1: 2*x, 2: 3*x}
x
在您创建 book
时是 Symbol('x')
.以后将 x
设置为 2
并不重要.
x
was Symbol('x')
when you created book
. It doesn't matter that you later set x
to 2
.
在您的其他情况下,如果我理解正确:
In your other case, if I understand you right:
x=Symbol('x')
x=2
book={1:2*x,2:3*x}
print(book) >>> {1:2*x,2:3*x}
结果:
{1: 4, 2: 6}
当您构建 book
时,
x
现在是 2
,因此您的结果现在与 sympy
无关.它只是常规的 Python 算术,因此您可以在字典中获得计算值.
x
is now 2
when you build book
, so your result now has nothing to do with sympy
. It's just regular Python arithmetic, and so you get computed values in your dict.
如果你想要的是{1: 4, 2: 6}
,你为什么要使用sympy
?
If what you want is {1: 4, 2: 6}
, why are you using sympy
at all?
要回答您的最后一个问题,您要问为什么添加行 book = book
不会改变结果.为什么会呢?那条线没有任何作用.book
在该行运行后与之前的值相同.
To answer your final question, you're asking why adding the line book = book
doesn't change the result. Why would it? That line doesn't do anything. book
is the same value after that line is run that it was before.
这篇关于为 `x` 赋值不计算总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!