简体   繁体   English

再次运行循环

[英]Run a loop again

I am trying to rerun a loop in python when it's on the last iteration but it's not working. 我试图在最后一次迭代时重新运行python中的循环,但它不起作用。 Here's my code: 这是我的代码:

primes = [i for i in range(2, 1001)]
p = 2
for i in range(p, len(primes), p):
    primes[i] = 0
    if i == len(primes)-1 and (p+1) <= max(primes):
        p += 1
        print(p)
print(primes)

The code only runs once as the print(primes) shows that every 2nd value is made 0. I want it to rerun until p is not equal to the maximum value in the list. 代码只运行一次,因为print(primes)显示每个第二个值都为0.我希望它重新运行,直到p不等于列表中的最大值。

primes = [2, 3]
upto = 1000
for num in range(4, upto+1):
    if all(num % p for p in primes):
        primes.append(num)

print(primes)

Note that this could still be improved by not testing for division by primes > sqrt(num) 请注意,仍然可以通过不按素数> sqrt(num)测试除法来改善这一点

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM