[英]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
具有对破烂行的内置处理。
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.