簡體   English   中英

為什么我從for循環中收到IndexError?

[英]Why am I getting an IndexError from a for loop?

我正在編寫將從csv文件中獲取日期和數值並進行比較的代碼。

date_location = 3
numeric_location = 4

with open('file1.csv', 'r') as f1:
    next(f1)
    with open('file2.csv', 'r') as f2:
        next(f2)
        for i in (f1):
            f1_date = (i.split()[date_location])
            f1_number = (i.split()[numeric_location])
            for j in (f2):
                f2_date = (j.split()[date_location])
                f2_number = (j.split()[numeric_location])
                print(f1_date, f1_number)
                print(f2_date, f2_number)
                if f1_date == f2_date:
                    print(f1_date == f2_date)
                    if f2_number > f1_number:
                        print('WIN')
                        continue
                    elif f2_number <= f1_number:
                        print('lose')
               f2.seek(0, 0)`

我收到此錯誤IndexError: list index out of range f1_date = (i.split()[date_location]) IndexError: list index out of range ,我認為這也會影響:

f1_number = (i.split()[numeric_location])

f2_date = (j.split()[date_location])

f2_number = (j.split()[numeric_location])

誰能解釋為什么? 我還沒有找到一種實現方法,因此不會顯示此錯誤。

編輯:我忘記了使用文本文件處理for循環后更改.split()的分隔符

兩種主要可能性:

1)您的csv文件不是用空格分隔的,並且.split()的默認分隔符是" " ,因此i.split()中至少不能有4個以空格分隔的項目(對於numeric_location 5個)。

2)您的csv是用空格分隔的,但參差不齊,即它的行不完整,因此對於某些行,第4列沒有數據。

我也強烈建議使用一個庫來讀取csvs。 csv在標准庫中,並且pandas具有對破爛行的內置處理。

發生錯誤是因為在i.split()情況下,您只有一個元素,但是date_location等於3。

您需要在str.split方法中基於您的csv文件添加分隔符。

您可以在這里了解更多信息

f1_number = (i.split()[numeric_location])

這在一行中做了很多事情。 我建議您將其分為兩行:

f1 = i.split()
f1_number = f1[numeric_location]
f1_date = f1[date_location]

現在,您將看到其中哪些導致了問題。 您應該添加一個print(f1)來查看拆分后的值。 它很可能沒有您認為的那么多元素。 否則您的索引偏離了應有的值。

對i.split()的調用將生成一個新列表,其中將包含字符串i中的每個單詞。 所以

"this is an example".split() == ["this", "is", "an", "example"]

您正在嘗試訪問結果列表的第三個元素,並且索引錯誤告訴您該列表的成員少於四個。 我建議打印i.split()的結果。 這很可能是一個偶然的錯誤,或者文件的第一行包含的內容與預期的有所不同。

同樣,默認情況下split()也會在空格上分割,因為您有一個csv,您可能想執行split(',')。

暫無
暫無

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

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