【问题标题】:Python: Associativity of (**) not behaving as desiredPython:(**)的关联性未按预期运行
【发布时间】:2014-04-11 11:34:06
【问题描述】:

我有这个代码:

from __future__ import print_function

a = lambda i=1: print('Line 1') or i if i else 1
b = lambda j=1: print('Line 2') or j if j else 2
c = lambda k=1: print('Line 3') or k if k else 3
d = lambda l=1: print('Line 4') or l if l else 4

q = a(True)**b(True)**c(True)**d(True)

运算符** 是右结合的。因此,当解析器/解释器遍历q 中给出的字符串时,它应该调用d,然后是c,然后......最后是a。正确的?没有。

它打印: 1号线 2号线 3号线 4号线

这一切的开始是我认为我可以想出一个非常聪明的方法来滥用运算符关联性,以便在将字符串放在同一连续行上的同时向后打印字符串,following the instructions from this closed golf post

【问题讨论】:

  • 右联想,即x**y**z == x**(y**z)。你不知道的是x**y 中的左侧总是在右侧之前评估。现在,问题是什么?
  • 哦!将来,是否有文件显示这些比较?我寻找它,但找不到确切的来源。

标签: python


【解决方案1】:

借用What is the associativity of Python's ** operator?

在幂和一元运算符的无括号序列中, 运算符从右到左求值(这不限制 操作数的评估顺序)。

这里有一些可以做你想做的事情 -

from __future__ import print_function

print_list = [
    lambda: print('Line 1') ,
    lambda: print('Line 2') ,
    lambda: print('Line 3') ,
    lambda: print('Line 4') ,
    ]

_ = [f() for f in print_list[::-1]]

【讨论】:

    【解决方案2】:

    Python specifies that expressions are, in general, evaluated left-to-right. 因此,** 运算符序列的操作数将从左到右进行计算。

    语言规范在the description of the power operator中有这个注释:

    因此,在不带括号的幂运算符和一元运算符序列中,运算符从右到左计算(这不限制操作数的计算顺序):-1**2 的结果为 -1

    注意有关操作数的评估顺序的部分。所以 Python 像这样评估a ** b ** c

    t1 = a
    t2 = b
    t3 = c
    t4 = t2 ** t3
    t5 = t1 ** t4
    

    t5 是表达式的值。

    【讨论】:

    • “Python 没有指定计算二元运算符操作数的顺序” - yes it does。它不做的是将运算符的优先级或关联性与评估顺序联系起来。
    • 我在谷歌搜索中找不到那个。感谢您的链接。我已经修改了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多