遍历列表与范围[重复]时行为上的差异

问题描述 投票:1回答:1

几年后,我一直回到python,并想编写一个简单的脚本来打印出1到n之间的所有素数。

我确实完成了,但是必须进行的一项代码更改使我感到困惑。当我循环通过范围1:n时,我得到正确的输出。但是,当我遍历一个列表(范围(1:n))时,它会中断。不知道我是否缺少一些愚蠢的东西...

代码的工作版本如下

#Choose max number to check
n = 100

#Initialize list of all potential primes 
primes = list(range(1,n))

#Loop through each potential prime
for i in range(1,n):
    j = 2
    #Divide each potential by every number below it from 2 up to i - 1, if the modulus is 0, then number is divisible, so remove from list of potential primes.
    while j < i:
        if i % j == 0:
            if i in primes: primes.remove(i)
            break
        j += 1
print(primes)

在主循环中,我们在range(1,n)中循环遍历i。但是,如果改为尝试遍历列表素数,如下面的代码示例所示,它将奇怪地返回9、39、69、99和其他以9结尾的数字为质数。

#Choose max number to check
n = 100

#Initialize list of all potential primes 
primes = list(range(1,n))

#Loop through each number in full list
for i in primes:
    j = 2
    #Divide each potential prime by every number below it from 2 up to i - 1, if the modulus is 0, then number is divisible, so remove from list of potential primes.
    while j < i:
        if i % j == 0:
            if i in primes: primes.remove(i)
            break
        j += 1
print(primes)

欢迎就改进(性能或其他方面)发表其他评论-正如我说的,我只是想尝试一些简单的事情。

python python-3.x loops primes
1个回答
0
投票

两个程序change primes随着它们的进展;第二个程序使用primes控制循环,而第一个则不。

© www.soinside.com 2019 - 2024. All rights reserved.