python - Does it make any difference if we change the position of operands in a logical statement?
问题描述
I wrote the following function in python which returns a sublist (i.e. the part of the list that it had been iterating through until it finds a particular value (in my case 5) without including it in the sublist and also stops iterating further).
def sublist(a):
b=[]
i=0
while(a[i]!=5 and i<=len(a)-1):
b.append(a[i])
i=i+1
return b
the above function worked fine with all test cases except this one a=[1, 6, 2, 3, 9]
. It gave the following error: IndexError: list index out of range
.
But when I interchanged the operands of the while loop condition and wrote the same code in the following way I got output for all the test cases:
def sublist(a):
b=[]
i=0
while(i<=len(a)-1 and a[i]!=5):
b.append(a[i])
i=i+1
return b
Why didn't I get output in the first case?
解决方案
这被称为“逻辑短路”,当一个逻辑表达式必须被评估时,编程语言观察第一个操作数并说:“这是一个 OR,如果第一个操作数对我来说没问题,那么整个表达式也没问题!” 所以它忽略了第二个。
对于 AND 是一样的,但是:“这是一个 AND,如果第一个操作数没问题,我必须检查第二个,否则整个表达式不正确”
在这种情况下,您首先检查 a[i]
可能
抛出异常,然后为 i<=len(a)-1。
我做了一点ELI5。
编辑:我忘了如果你不使用括号也看这个表https://en.wikipedia.org/wiki/Logical_connective#Order_of_precedence
同样作为一名计算机科学家,您必须对短路有很好的了解,它可以帮助您进行很多表演
推荐阅读
- laravel - instagram embed 不会向下滚动,直到评论部分
- caching - 分布式运行器缓存 Gitlab Runner Path = path/to/prefix
- reactjs - firebase auth lib 上缺少类型
- powerbi - 由于“无法确定表 YY 中列 XX 的单个值”,RANKX 无法正常工作
- python - 如何用基于索引的列表值替换二维数组的值
- flutter - 是否可以在不使用“小部件”的情况下使用 Statefulwidget 中另一个页面的传递数据。
- python-3.x - numpy seterrcall,如何标记导致flouting点错误的对象?
- excel - df.to_excel 创建 12MB 文件。再次打开和保存时文件突然缩小到 4.6 MB
- android - 从后台获取应用程序区域设置时会更新
- sql - 更新两个表的数据