博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python是否支持短路?
阅读量:3579 次
发布时间:2019-05-20

本文共 4947 字,大约阅读时间需要 16 分钟。

本文翻译自:

Python是否支持布尔表达式短路?


#1楼

参考:


#2楼

Short-circuiting behavior in operator and , or : 操作符and的短路行为, or

Let's first define a useful function to determine if something is executed or not. 我们首先定义一个有用的函数来确定是否执行了某些操作。 A simple function that accepts an argument, prints a message and returns the input, unchanged. 一个简单的函数,它接受一个参数,打印一条消息并返回输入,且未更改。

>>> def fun(i):...     print "executed"...     return i...

One can observe the of and , or operators in the following example: 在以下示例中,可以观察 and or运算符 :

>>> fun(1)executed1>>> 1 or fun(1)    # due to short-circuiting  "executed" not printed1>>> 1 and fun(1)   # fun(1) called and "executed" printed executed1>>> 0 and fun(1)   # due to short-circuiting  "executed" not printed 0

Note: The following values are considered by the interpreter to mean false: 注意:解释器认为以下值表示false:

False    None    0    ""    ()    []     {}

Short-circuiting behavior in function: any() , all() : 函数中的短路行为: any()all()

Python's and functions also support short-circuiting. Python的和函数还支持短路。 As shown in the docs; 如文档所示; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. 他们按顺序评估序列中的每个元素,直到找到可以尽早退出评估的结果。 Consider examples below to understand both. 考虑下面的示例以了解两者。

The function checks if any element is True. 函数检查是否有任何元素为True。 It stops executing as soon as a True is encountered and returns True. 一旦遇到True,它将立即停止执行并返回True。

>>> any(fun(i) for i in [1, 2, 3, 4])   # bool(1) = TrueexecutedTrue>>> any(fun(i) for i in [0, 2, 3, 4])   executed                               # bool(0) = Falseexecuted                               # bool(2) = TrueTrue>>> any(fun(i) for i in [0, 0, 3, 4])executedexecutedexecutedTrue

The function checks all elements are True and stops executing as soon as a False is encountered: 函数检查所有元素是否为True,并在遇到False时立即停止执行:

>>> all(fun(i) for i in [0, 0, 3, 4])executedFalse>>> all(fun(i) for i in [1, 0, 3, 4])executedexecutedFalse

Short-circuiting behavior in Chained Comparison: 链式比较中的短路行为:

Additionally, in Python 此外,在Python中

; ; for example, x < y <= z is equivalent to x < y and y <= z , except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). 例如, x < y <= z等效于x < y and y <= z ,除了y仅被评估一次(但是在两种情况下,当x < y被发现为假时, z都不被评估)。

>>> 5 > 6 > fun(3)    # same as:  5 > 6 and 6 > fun(3)False                 # 5 > 6 is False so fun() not called and "executed" NOT printed>>> 5 < 6 > fun(3)    # 5 < 6 is True executed              # fun(3) called and "executed" printedTrue>>> 4 <= 6 > fun(7)   # 4 <= 6 is True  executed              # fun(3) called and "executed" printedFalse>>> 5 < fun(6) < 3    # only prints "executed" onceexecutedFalse>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it againexecutedexecutedFalse

Edit: 编辑:

One more interesting point to note :- Logical operators in Python returns an operand's value instead of a Boolean ( True or False ). 一个更有趣的一点需要注意: -逻辑运营商在Python返回一个操作数的 ,而不是一个布尔值( TrueFalse )。 For example: 例如:

Operation x and y gives the result if x is false, then x, else y if x is false, then x, else y操作x and y给出结果if x is false, then x, else y

Unlike in other languages eg && , || 与其他语言(例如&&|| operators in C that return either 0 or 1. C中的运算符返回0或1。

Examples: 例子:

>>> 3 and 5    # Second operand evaluated and returned 5                   >>> 3  and ()()>>> () and 5   # Second operand NOT evaluated as first operand () is  false()             # so first operand returned

Similarly or operator return left most value for which bool(value) == True else right most false value (according to short-circuiting behavior), examples: 同样or运算符返回最左边的值,其中bool(value) == True否则返回最右边的假值(根据短路行为),示例:

>>> 2 or 5    # left most operand bool(2) == True2    >>> 0 or 5    # bool(0) == False and bool(5) == True5>>> 0 or ()()

So, how is this useful? 那么,这有什么用呢? One example use given in By Magnus Lie Hetland: Magnus Lie Hetland在《 给出的一个示例用法:

Let's say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<unknown>' . 假设用户应该输入他或她的名字,但可能选择不输入任何内容,在这种情况下,您要使用默认值'<unknown>' You could use an if statement, but you could also state things very succinctly: 您可以使用if语句,但也可以非常简洁地陈述一下:

In [171]: name = raw_input('Enter Name: ') or '
'Enter Name: In [172]: nameOut[172]: '
'

In other words, if the return value from raw_input is true (not an empty string), it is assigned to name (nothing changes); 换句话说,如果raw_input的返回值是true(不是空字符串),则将其分配给name(不变);否则,它将返回true。 otherwise, the default '<unknown>' is assigned to name . 否则,默认的'<unknown>'被分配给name


#3楼

Yes. 是。 Try the following in your python interpreter: 在您的python解释器中尝试以下操作:

and

>>>False and 3/0False>>>True and 3/0ZeroDivisionError: integer division or modulo by zero

or 要么

>>>True or 3/0True>>>False or 3/0ZeroDivisionError: integer division or modulo by zero

#4楼

是的, andor运算符都短路-请参阅 。

转载地址:http://zelgj.baihongyu.com/

你可能感兴趣的文章
项目整合微信扫码登录功能
查看>>
分布式文件系统FastDfs的搭建
查看>>
Springboot项目利用Java客户端调用FastDFS
查看>>
全文检索工具elasticsearch的安装和简单介绍
查看>>
利用Kibana学习全文检索工具elasticsearch
查看>>
SpringBoot在Test测试类或自定义类中通过@Autowired注入为null
查看>>
使用docker搭建YAPI服务
查看>>
西南科技大学OJ题 邻接表到邻接矩阵1056
查看>>
西南科技大学OJ题 有向图的出度计算1057
查看>>
西南科技大学OJ题 有向图的最大出度计算1059
查看>>
西南科技大学OJ题 带权有向图计算1063
查看>>
oracle主键自增触发器编写
查看>>
String与StringBuilder与StringBuffer三者的差别
查看>>
各种IO流之间的关系和区别
查看>>
SSM如何实现上传单图片
查看>>
SSM环境下java如何实现语音识别(百度语音识别版)
查看>>
ajax方法参数的用法和他的含义
查看>>
数据库基础技巧及用法
查看>>
实用方法:无request参数时获得当前的request的方法
查看>>
JS操作数组常用实用方法
查看>>