Python - Modulo Operation as a Conditional(Python - 作为条件的模运算)
问题描述
我在 lambda 函数测试素数中看到了模运算符的这种用法.如果据我所知这不是一个实际的布尔语句,有人可以解释为什么只要 i 大于 x 就会执行以下语句.如果分子大于分母,无论它们是否为因数,它也适用于除法.
I saw such a use of the modulo operator in a lambda function testing for primality. Can someone explain why the following statement will execute as long as i is greater than x if this isn't to my knowledge an actual boolean statement. It works with division as well if the numerator is greater than the denominator regardless if they are factors or not.
if x % i:
# Execute random foolishness
注意:我只在 Python 和 Java 中尝试过,所以如果这适用于另一种语言,我深表歉意,因为它可能不是特定于语言的问题.
NOTE: I have only tried this in Python and Java so if this works in another language I apologize as it is probably not a language specific question.
推荐答案
Python 将非零值视为 True,因此 if x % i:
与 if x % i 相同!= 0:
.这只是测试 x
是否可以被 i
整除的快速方法.
Python treats non-zero values as True, so if x % i:
is the same as if x % i != 0:
. It's just a quick way to test if x
is evenly divisible by i
.
这篇关于Python - 作为条件的模运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python - 作为条件的模运算


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01