[英]Why am I getting the error “list index out of range”?
我编写了一个程序,应该打印出从 0 到 100 的所有合数,但我不断收到错误“列表索引超出范围”
我能做些什么来解决它?
def isPrime(x):
if x==0:
return False
if x==1 or x==2:
return True
for i in range(2, x):
if x%i==0:
return False
break
elif x%i==1:
return True
else:
print("error")
i=0
num = list(range(100))
while i<100:
if isPrime(num[i]==True): #I get the error here
del (num[i])
i += 1
else:
i += 1
print(num)
因为如果您的条件为真,您将删除一个元素,但仍在增加i
。 将您的代码更改为以下内容:
def isPrime(x):
if x==0:
return False
if x==1 or x==2:
return True
for i in range(2, x):
if x%i==0:
return False
return True
i=0
lim = 100
num = list(range(lim))
while i<lim:
if isPrime(num[i])==True: #I get the error here
del (num[i])
lim -=1
else:
i += 1
print(num)
顺便说一句, if isPrime(num[i]==True)
,您的代码包含错误。
Output:
[0, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99]
由于您的isPrime
算法也不正确,因此我已对其进行了更正。
因为您在循环访问列表时正在编辑列表。 在索引 74 处,该索引不再存在,因为列表的长度为 73。请注意,您的素数 function 似乎无法按您的预期工作。
from math import sqrt
from itertools import count, islice
def isPrime(n): # Taken from https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python/27946768#27946768
if n < 2:
return False
for number in islice(count(2), int(sqrt(n) - 1)):
if n % number == 0:
return False
return True
num = list(range(100))
to_delete = []
for i in num:
if isPrime(i): #I get the error here
to_delete.append(i)
final = [n for n in num if n not in to_delete]
print(final)
正确的 output:
[0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.