简体   繁体   English

为什么我从for循环中收到IndexError?

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

I'm writing code that will take dates and numeric values from a csv file and compare them. 我正在编写将从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)`

I get this error IndexError: list index out of range for f1_date = (i.split()[date_location]) , which i assume will also affect: 我收到此错误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])

Can anyone explain why? 谁能解释为什么? I haven't found a way to make it so this error doesn't show. 我还没有找到一种实现方法,因此不会显示此错误。

EDIT: I forgot to change the separator for .split() after messing around with the for loop using text files 编辑:我忘记了使用文本文件处理for循环后更改.split()的分隔符

Two main possibilities: 两种主要可能性:

1) Your csv files are not space delimited, and as the default separator for .split() is " " , you will not have at least 4 space-separated items in i.split() (or 5 for numeric_location ). 1)您的csv文件不是用空格分隔的,并且.split()的默认分隔符是" " ,因此i.split()中至少不能有4个以空格分隔的项目(对于numeric_location 5个)。

2) Your csv is space delimited, but is ragged, ie it has incomplete rows, so for some row, there is no data for column 4. 2)您的csv是用空格分隔的,但参差不齐,即它的行不完整,因此对于某些行,第4列没有数据。

I also highly suggest using a library for reading csvs. 我也强烈建议使用一个库来读取csvs。 csv is in the standard library, and pandas has built-in handling of ragged lines. csv在标准库中,并且pandas具有对破烂行的内置处理。

The error is happening because you only have one element in the case of i.split() But date_location is equal to 3. 发生错误是因为在i.split()情况下,您只有一个元素,但是date_location等于3。

You need to add a separator based on your csv file in the str.split method. 您需要在str.split方法中基于您的csv文件添加分隔符。

You can read more about it here 您可以在这里了解更多信息

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

This is doing a lot in a single line. 这在一行中做了很多事情。 I suggest you split this into two lines: 我建议您将其分为两行:

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

Now you will see which of these causes the problem. 现在,您将看到其中哪些导致了问题。 You should add a print(f1) to see the value after the split. 您应该添加一个print(f1)来查看拆分后的值。 Most likely it doesn't have as many elements as you think it does. 它很可能没有您认为的那么多元素。 Or your indexes are off from what they should be. 否则您的索引偏离了应有的值。

The call to i.split() is going to generate a new list, which will contain each word of the from the string i. 对i.split()的调用将生成一个新列表,其中将包含字符串i中的每个单词。 So 所以

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

You are trying to access the third element of the resulting list, and the index error tells you that this list has less than four members. 您正在尝试访问结果列表的第三个元素,并且索引错误告诉您该列表的成员少于四个。 I suggest printing the result of i.split(). 我建议打印i.split()的结果。 Very likely this is either an off by one error, or the first line of your file contains something different than what you are expecting. 这很可能是一个偶然的错误,或者文件的第一行包含的内容与预期的有所不同。

Also split() by default will split on whitespace, given that you have a csv you may have wanted to do split(','). 同样,默认情况下split()也会在空格上分割,因为您有一个csv,您可能想执行split(',')。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM