簡體   English   中英

python 文件閱讀列表索引錯誤:索引超出范圍

[英]python file reading list index error: index out of range

我遇到以下代碼錯誤:

h = 0
num = 0
with open('file1') as f:

    for row in f.readlines():
        line = row.split()

        print(line)

        # check for new
        if int(float(line[0])) != h:
            h = int(float(line[0]))
            num += 1

OUTPUT:

['3', '1', '35', '31.924847576898625', '5.128603105085375', '6.20101', '0.7821899999999999', '0.23388931803044988']
[]
Traceback (most recent call last):
  File "phase_one.py", line 45, in <module>
    if int(float(line[0])) != h:
IndexError: list index out of range

為什么我調用 print() 時,打印了實際的行,但后面還打印了一個空列表 '[]',這是導致此錯誤的原因?

您的文件中有兩行。 第一行是第一行。 文件的第二行是空白的。 任何一個

  1. 刪除該行
  2. 或者,在嘗試訪問其第一個元素之前檢查line是否為空。 空列表是虛假的,因此您可以簡單地執行if line and int(line[0])...並且短路將處理 rest。
line = row.split()
print(line)

if line and int(line[0]) != h:
    h = int(line[0])
    num += 1
  1. 或者,捕獲引發的錯誤。
line = row.split()
print(line)

try:
    if int(line[0]) != h:
        h = int(line[0])
        num += 1
except IndexError:
    pass

此外,您不需要在將字符串轉換為int之前將其轉換為float 只需if int(line[0]):= h:就足夠了。

暫無
暫無

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

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