Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

python - Assigning value to `x` doesn't calculate sum

I have the following problem:

x=Symbol('x') 
book={1:2*x,2:3*x}
x=2
print(book) >>> {1:2*x,2:3*x}

I had hoped it would print {1:4,2:6}

But if I set book={1:2*x,2:3*x} just before the print statement, I get the wanted result.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

Result:

{1: 2*x, 2: 3*x}

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}

Result:

{1: 4, 2: 6}

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.

If what you want is {1: 4, 2: 6}, why are you using sympy at all?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...