Python中boolean'和','或'的运算符方法是什么?

kle*_*len 3 python parsing operator-keyword

例如,这些在运算符模块中定义,可以这样使用:

import operator
print operator.__add__   # alias add -> +
print operator.__sub__   # alias sub -> -
print operator.__and__   # alias and_ -> &
print operator.__or__    # alias or_ -> |
Run Code Online (Sandbox Code Playgroud)

那么什么是相当于andor

print operator."and ?????"  # should be boolean-and
print operator."or ????"    # should be boolean-or
Run Code Online (Sandbox Code Playgroud)

Ned*_*der 12

andor运营商没有操作模块中的等价物,因为它们不能作为一个功能来实现.这是因为它们是短路的:它们可能不会根据第一个操作数的结果来评估它们的第二个操作数.


e-s*_*tis 6

这些不存在.你能做的最好的事就是用lambda代替它们:

band = (lambda x,y: x and y)
bor = (lambda x,y: x or y)
Run Code Online (Sandbox Code Playgroud)

原因是你无法实现完整的行为,and或者or因为它们可能会短路.

例如:

if variable or long_fonction_to_execute():
    # do stuff
Run Code Online (Sandbox Code Playgroud)

如果variable是的话True,long_fonction_to_execute永远不会被调用,因为Python知道而不是or必须返回True.这是一个优化.在大多数情况下,这是一个非常理想的功能,因为它可以节省大量无用的处理.

但这意味着你不能使它成为一个功能:

例如:

if bor(variable, long_fonction_to_execute()):
    # do stuff
Run Code Online (Sandbox Code Playgroud)

在这种情况下,long_fonction_to_execute甚至在评估之前就会调用它.

幸运的是,鉴于您使用生成器和列表推导这一事实,您很少需要类似的东西.

  • 当然,那些不会短路. (2认同)