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 - 作为条件的模运算


基础教程推荐
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01