簡體   English   中英

為什么我收到錯誤“列表索引超出范圍”?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM