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


- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01