python - 为什么 for 循环可以在 all() 中处理空集?

标签 python

这里是Python新手。所以我正在读Whirlwind Tour of Python

还有一个例子:

def gen_primes(N):
    """Generate primes up to N"""
    primes = set()
    for n in range(2, N):
        if all(n % p > 0 for p in primes):
            primes.add(n)
            yield n

print(*gen_primes(100))

对于这一行:if all(n%p>0 for p in primes),我想 primes 仍然是空的,为什么 for 循环仍然有效?

最佳答案

根据 all() 文档:

Return True if all elements of the iterable are true (or if the iterable is empty).

在您的情况下,底层生成器产生一个空值,它就像 all([])all(set()) 因此,一个空的迭代器传递到 all() 内置。

您很可能正在寻找这个,因此您首先检查它是否不为空,然后根据某种条件检查所有元素。

if primes and all(...):

尽管如注释中所述,在您的特定代码中,这会导致 if False,因此您需要稍微重写实现或将条件拆分为两个 IF。


如果您喜欢 C,您可能会发现 the underlying all() implementation 很有趣,尤其是 this part 我认为它只是退出循环,从而导致 return True

有点像这样:

for _ in iterable:
    # here check for false and return
# aaand the iterable is empty, so meh
# no loop and falls directly to the last return
return True

关于python - 为什么 for 循环可以在 all() 中处理空集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68786420/

相关文章:

python - 在 OpenMDAO 1.x 中链接来自两个组的 IndepVarComp

python - OpenCV-Python 密集 SIFT

python - 在 DataFrame 索引中查找标签位置时,searchsorted 是否比 get_loc 更快?

python - 在 Python 中,我可以调用导入模块的 main() 吗?

python - 如何在不导入的情况下从python文件中获取函数

python - 如何将灰度 matplotlib 图保存到 numpy 数组

python - Groupby 类和计数特征中的缺失值

python - 在整个测试套件或 unittest/pytest 中的 at_exit 之后运行命令的 Hook

python - 使用 PKCS#7 填充的 Python 3 中的 AES-CBC 128、192 和 256 加密解密

Python Pandas 数据阅读器不工作