Traceback (most recent call last):
File "C:\Users\michael.ramage\Desktop\Carbon.py", line 12, in <module>
carbon_i = float(X[3])
IndexError: list index out of range我正在从一个记事本文件中读取数据,以便用于matlab。我所掌握的数据是关于碳的(以ppm计)。每年,每天都要取一个碳的平均值,然后再取一个月的平均值。这方面的资料每年报告12次。例如,在1960年,每个月都有自己的测量方法。我只想要第一列(年份)和第四列(二氧化碳含量)-指数0和3。这个文本文件很长。从2017年到9个月。如果我能附上一个文件,我会的。
1960 1 1960.042 316.43 316.43 316.51 -1
1960 2 1960.125 316.97 316.97 316.47 -1
1960 3 1960.208 317.58 317.58 316.49 -1
1960 4 1960.292 319.02 319.02 316.86 -1
1960 5 1960.375 320.03 320.03 317.24 -1
1960 6 1960.458 319.59 319.59 317.36 -1
1960 7 1960.542 318.18 318.18 317.30 -1
1960 8 1960.625 315.91 315.91 316.92 -1
1960 9 1960.708 314.16 314.16 316.87 -1
1960 10 1960.792 313.83 313.83 316.76 -1
1960 11 1960.875 315.00 315.00 316.98 -1
1960 12 1960.958 316.19 316.19 317.13 -1
info = {}
s=" "
with open("data.txt") as inData:
while s != "":
average = 0
for line in range(12):
s = inData.readline()
x = s.rstrip("\n").split()
carbon_i = float(x[3]) #the error occurs here
average += carbon_i
if line == 12:
info[x[0]] = average
else:
pass
print("done")在上面的代码中,我读取一行(并删除\n),然后剥离它以创建一个列表,以便我可以使用它的索引。我想要平均每个月的二氧化碳含量(以ppm计)。例如,我将获取所提供数据的索引3,并将其平均化。之后,我把年份(键)和平均值(值)放在字典里。关键将是年份,12个月的平均碳排放量将是计算值。
发布于 2017-11-03 20:51:41
您的问题是,当遇到空行时,while循环的主体将继续执行。下面是一个可以解决这一问题的调整:
info = {}
s=" "
with open("data.txt") as inData:
while True:
average = 0
for line in range(12):
s = inData.readline() # this could be a blank line
x = s.rstrip("\n").split() # if s is blank, x is an empty list
try:
carbon_i = float(x[3]) # if x is empty, this will cause an error
except IndexError:
break # handle the error by exiting the while loop
average += carbon_i
if line == 12:
info[x[0]] = average
else:
pass
print("done")值得注意的是:如果文件中没有空行,则此循环不会结束。
https://stackoverflow.com/questions/47104101
复制相似问题