简体   繁体   English

当我改变我正在迭代的列表时,如何避免代码中的列表错误功能?

[英]How can I avoid the list error function in my code as I alter a list I am iterating?

I am looking to use pop and remove functions to remove numbers from the list 2 to 100 in order to get a list of prime numbers. 我希望使用弹出和删除功能从列表2到100中删除数字,以获得素数列表。 The main problem is that k always ends up causing an error. 主要问题是k总是最终导致错误。 Also, when a put a print function after k , it shows up only even numbers, not sure why that is happening. 此外,当在k之后放置打印功能时,它仅显示偶数,不确定为什么会发生这种情况。

x=[] 
for i in range(2,100): 
    x.append(i)

primes=[]

count=0

while count < 99:
    k = x[count]
    print(k)
    primes.append(k)
    """for j in range(2,100):
        if k % j ==0:
            x.remove(j)"""
    x.pop(count)
    count = count + 1

print(x)

Errors can happen because you are removing elements from a list while iterating over it. 错误可能发生,因为您在迭代它时从列表中删除元素。

Consider a list [x, y, z] and you're at position 0. If you decide to remove the element at position 0 then Python will move on to check position 1 in the next iteration of the loop. 考虑一个列表[x, y, z] ,你就在位置0.如果你决定删除位置0的元素,那么Python将继续检查循环的下一次迭代中的位置1。 But position then refers to element z (because position 1 in the list [y, z] is z , not y ). 但是,position会引用元素z (因为列表[y, z]中的位置1是z ,而不是y )。

Your out of range: 你超出范围:

x len is 98, and the while loop counts for 48 times.... x len是98, while循环计数48次....

You can fix it easily like that (Just fixed the While condition to count < 48 ): 您可以像这样轻松修复它(只需将While条件修复为count < 48 ):

    x=[]
    for i in range(2,100):
        x.append(i)

    primes=[]

    print len(x)

    count=0

    while count < 48:
        k = x[count]
        print(k)
        primes.append(k)
        """for j in range(2,100):
            if k % j ==0:
                x.remove(j)"""
        x.pop(count)
        count = count + 1

    print(x)

You aren't testing for prime numbers at all. 您根本没有测试素数。 You're getting only even numbers cause you're removing all odd ones. 你只得到偶数,因为你正在删除所有奇数。 From the logic point there's no need to pre-polulate the list to further remove unwanted elements. 从逻辑点来看,不需要预先列出列表以进一步删除不需要的元素。

Here's what you're looking for: 这是你要找的东西:

def is_prime(n):
    if n < 2 or (n % 2) == 0:
        return n == 2

    f = 3

    while (f * f) <= n:
        if (n % f) == 0:
            return False

        f += 2

    return True

primes = [n for n in range(2, 100) if is_prime(n)]
print(primes)

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

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