[英]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.