簡體   English   中英

我得到:IndexError: list index out of range,但我不知道為什么,它不會影響輸出

[英]I got: IndexError: list index out of range, but I don't know why and it doesne't apper to affect the output

我正在制作一個程序來計算來自外部 .txt 文件的數字差異的平均值。 我寫了這個,突然我收到一個索引錯誤。 我想我知道這個的意思,索引不存在。 不知道錯在哪里...

此外,錯誤出現很奇怪並且被其他輸出(打印)中斷,我不知道為什么會發生這種情況......

名單在這里:

111
222
333
444
555
666
777
888
999

代碼:

file = open("list", "r")
lst = file.read().split("\n")

index = 0

for i in lst:
    num1 = lst[index]

    index += 1

    num2 = lst[index]

    print("NUM1:" + str(num1))
    print("NUM2:" + str(num2))

    dif = int(num2) - int(num1)

    print(dif)

輸出看起來沒有錯誤的任何影響......

Traceback (most recent call last):  
NUM1:111  
  File "FILE_LOCATION", line 11, in <module>  
NUM2:222  
    num2 = lst[index]  
111  
IndexError: list index out of range  
NUM1:222  
NUM2:333  
111  
NUM1:333  
NUM2:444  
111  
NUM1:444  
NUM2:555  
111  
NUM1:555  
NUM2:666  
111  
NUM1:666  
NUM2:777  
111  
NUM1:777  
NUM2:888  
111  
NUM1:888  
NUM2:999  
111  

Process finished with exit code 1  

還有一件事:錯誤是不可預測的,總是出現在不同的地方。 有時完全在開頭,有時在結尾,有時在整個輸出中。

對於每個元素,您檢查當前元素和下一個元素之間的差異。 但是,最后一個元素沒有下一個元素,因此出現錯誤。

您在輸出之前看到錯誤的原因可能是因為輸出進入標准輸出,錯誤進入標准錯誤,這是兩個不同的流,當您的應用程序崩潰時,它們會同時刷新。

輸出似乎沒有受到影響,因為您應該在最后一個元素處停止,但您沒有,因此程序在打印完所有內容后崩潰。

list1 = []
for line in x.readlines():
    line = line.replace("\n","")
    list1.append(line)
for i in range(len(list1)):
    if i+1<len(list1):
        s1 = int(list1[i])
        s2 = int(list1[i+1])
        print(f"Num1->{s1}")
        print(f"Num2->{s2}")
        dif = s2-s1
        print(dif)
    else:
        print("List is completed")

錯誤是因為索引錯誤,因為您在上面的示例代碼中將索引增加到 +1,並且該索引不在列表類型->lst 中。 這就是您收到此錯誤的原因。 試試這個代碼對你有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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