简体   繁体   English

在 all() function 中,“for”如何评估为真或假?

[英]How does 'for' evaluate to true or false in an all() function?

I am working through project Euler and have made it to problem #7 .我正在通过项目 Euler 并已解决问题 #7 I worked out a solution with the help of a video I found online, but there is one line of code that I don't understand.我在网上找到的视频的帮助下制定了一个解决方案,但是有一行代码我不明白。 Here is the problem and my solution.这是问题和我的解决方案。

"""By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?"""

primes = []
x = 2

while(len(primes)) < 10001:
    if all(x % prime for prime in primes):
        primes.append(x)
    x += 1

print(primes[-1])

I'm confused about the all() function.我对 all() function 感到困惑。 I know that x % prime will evaluate to true if the remainder is not zero, but what exactly is the function doing with the for statement?我知道如果余数不为零, x % prime将评估为 true,但是 function 究竟在用 for 语句做什么? Thanks in advance!提前致谢!

The function is using list comprehension . function 正在使用列表理解 It is taking each of the numbers from the array primes and defining them as prime .它从数组primes中获取每个数字并将它们定义为prime It then uses that to evaluate x % prime .然后它使用它来评估x % prime

Put into a for loop x % prime for prime in primes would look like:放入 for 循环x % prime for prime in primes看起来像:

for prime in primes:
    return x % prime

Next, all() checks if all of them equate truthy (or true).接下来, all()检查它们是否都等于真(或真)。 So if one of the returns from the for loop mentioned above is false, the entire if statement returns false.因此,如果上述 for 循环的返回值之一为 false,则整个 if 语句将返回 false。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么“False is False is False”评估为“True”? - Why does `False is False is False` evaluate to `True`? 为什么 (1 in [1,0] == True) 评估为 False? - Why does (1 in [1,0] == True) evaluate to False? 我如何在 Python 中不将 0 或 1 评估为 True 或 False - How do I in Python not evaluate 0 or 1 as True or False 使用Python方式检查是否:所有元素的评估结果均为False -OR-所有元素的评估结果均为True - Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True 如何将1和0映射为所有true和false - how to map 1 and 0 for all true and false 为什么“a == x or y or z”的计算结果总是为 True? 我如何将“a”与所有这些进行比较? - Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those? 为什么Python在if语句中将字符串/数字评估为True还是myNumber == True返回False? - Why does Python evaluate strings/numbers as True in if statements yet myNumber == True returns False? 如果内部调用的所有函数都为真,我如何编写一个返回真的函数,否则返回假/错误? - how do i write a function that returns true if all the functions called inside it are true, returns false/errror otherwise? 将False评估为-1和True为1的最佳方法是什么? - What is the best way to evaluate False as -1 and True as 1? 为什么 pd.Series([np.nan]) | pd.Series([True]) 评估为 False? - Why does pd.Series([np.nan]) | pd.Series([True]) evaluate to False?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM