【问题标题】:Difference in behaviour when looping through list vs range [duplicate]循环遍历列表与范围时的行为差异[重复]
【发布时间】:2019-12-26 18:28:16
【问题描述】:

几年后我又重新开始使用python,并想编写一个简单的脚本来打印1到n之间的所有素数。

我确实完成了它,但我必须进行的一项代码更改让我感到困惑。当我遍历范围 1:n 时,我得到了正确的输出。但是,当我遍历 list(range(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)

欢迎任何其他关于改进(性能或其他方面)的 cmets - 正如我所说的,我只是想重新投入一些简单的事情。

【问题讨论】:

  • 迭代时不要删除列表项
  • 这归结为您正在迭代一个集合 (primes),同时还通过删除元素来修改它。这绝不是一个好主意,在这种情况下,它会导致您跳过一些迭代。

标签: python python-3.x loops primes


【解决方案1】:

两个程序改变 primes 随着他们的进步;第二个程序使用primes 控制循环,而第一个程序没有。

【讨论】:

    猜你喜欢
    • 2013-05-03
    • 2016-01-01
    • 2015-10-17
    • 2018-08-23
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    相关资源
    最近更新 更多