简体   繁体   English

ValueError: list.remove(x): x 不在 Python 的列表中

[英]ValueError: list.remove(x): x not in list in Python

This is my code这是我的代码

lower = int(input('pleace input the beggest num:'))
upper = int(input('pleace input the smallest num:'))
lis=[]
for num in range(lower,upper):
    lis.append(num)
    for i in range(2,num-1):
        if num%i == 0:
            lis.remove(num) 
print(lis)

Which stop is wrong?哪个站错了?

I guess this programme is to find all primes between [lower, upper).我猜这个程序是为了找到 [lower, upper) 之间的所有素数。 And the problem in your code is that you should break the loop when you find x is not prime.你的代码中的问题是当你发现x不是质数时你应该打破循环。 such as:如:

if num%i == 0:
    lis.remove(num)
    break

If there is a number that's divisible by more than one number from range(2,num-1) , your program will try to remove it multiple times, but that value wouldn't be there after it's removed the first time.如果有一个数字可以被range(2,num-1)中的多个数字整除,您的程序将尝试多次删除它,但在第一次删除后该值将不存在。

For example, let's consider number 6. You add it to your list, then, in the for loop, you go from 2 to 4 (mind you, range excludes the upper limit.).例如,让我们考虑数字 6。将它添加到列表中,然后在for循环中从 2 变为 4(请注意, range不包括上限。)。 6 % 2 == 0 , so your if statement is true, so you remove that six from the list… but the loop continues. 6 % 2 == 0 ,所以你的if语句为真,所以你从列表中删除了那六个......但循环继续。 Then, it checks for 3, and 6 % 3 == 0 , too, so it tries to call lis.remove(6) … but that six is no longer there—you've removed it beforehand.然后,它还会检查 3 和6 % 3 == 0 ,因此它会尝试调用lis.remove(6) ……但是那个 6 已经不存在了——您已经事先将其删除了。

In the future, consider using a debugger for running your programs step-by-step, it will help you find your errors.将来,考虑使用调试器来逐步运行您的程序,它将帮助您发现错误。

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

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