这里是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/