简体   繁体   English

Python 中的算术求值顺序

[英]Arithmetic evaluation order in Python

I'd like this question answered just for curiosity's sake.我想回答这个问题只是为了好奇。 In the following mathematical expression (and ones like it):在以下数学表达式中(以及类似的):

(( (3 * 7)  + 5 * ((3 - 7) + (3 * 4))) + 9)

Does Python evaluate (3 - 7) or (3 * 4) first? Python 是先评估(3 - 7)还是(3 * 4) The thing about this is, these innermost parentheses could really be evaluated in either order and achieve the same result.关于这一点的事情是,这些最里面的括号确实可以按任一顺序进行评估并获得相同的结果。 But which order is used?但是使用哪个顺序?

At this point I'm considering putting a breakpoint in the actual Python interpreter to see if I can come up with any sort of answer (as to how the parse tree is generated).在这一点上,我正在考虑在实际的 Python 解释器中放置一个断点,看看我是否能想出任何类型的答案(关于解析树是如何生成的)。 Been asking on IRCs and such to no avail.一直在询问 IRC 等,但无济于事。 Thanks for your time.谢谢你的时间。

You can inspect the byte code to see that the left side is evaluated first:您可以检查字节码以查看左侧是首先评估的:

dis.dis("""(a - b) + (c * d)""")
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 BINARY_SUBTRACT
              6 LOAD_NAME                2 (c)
              8 LOAD_NAME                3 (d)
             10 BINARY_MULTIPLY
             12 BINARY_ADD
             14 RETURN_VALUE

The evaluation order of expressions is part of the language specification.表达式的求值顺序是语言规范的一部分。

Evaluation order 评估顺序

Python evaluates expressions from left to right. Python 从左到右计算表达式。 Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.请注意,在评估赋值时,右侧先于左侧进行评估。


Note that if you use a literal expression, such as (3 - 7) + (3 * 4) , it is not evaluated but directly compiled.请注意,如果您使用文字表达式,例如(3 - 7) + (3 * 4) ,则不会对其进行评估,而是直接编译。

dis.dis("""(3 - 7) + (3 * 4)""")
  1           0 LOAD_CONST               0 (8)
              2 RETURN_VALUE

It evaluates left-to-right, you can check with with input() calls:它从左到右评估,您可以使用input()调用进行检查:

>>> (( (3 * 7) + 5 * ((input('1')) + (input('2')))) + 9)
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM