IndexError: 列表索引超出范围,但我有足够的元素?!Python
def build_country_dict(lines):
'''Return a dictionary in form of {country: count}, where country is
the country code and count is the number of medals won by athletes
from that country'''
d = {} #Start with an empty dictionary
for i in range(1, len(lines)): #For i ranging from 1 to the length of lines
line_list = lines[i].split(',') # Split lines[i] into a list - split on comma
country = line_list[6] # Get the country
if country not in d: # If the country is not in the dictionary
d[country] = 0 # Add it with count of 0
d[country] = d[country] + 1 # Add one to the country count
return d #Return the dictionary
这个错误 IndexError: list index out of range
是指在访问 line_list[6]
时出错,但我用的这个列表里有11个元素,所以我不知道该怎么修正这个问题。
原始文件是一个csv文件,所以我用Excel检查了一下,发现每一行都应该变成一个包含11个元素的列表。不过这个文件太大了,我无法把所有的列表都打印出来。
我试着用一小部分来检查,打印 line_list[6]
,结果打印得很好。
1 个回答
2
lines[i]
似乎没有足够的数据来用 ',' 来分割。
试试这个代码,替代 country = line_list[6]
country = line_list[6] if len(line_list) > 6 else 'unknown'
另外,
try:
country = line_list[6]
except IndexError:
continue
这个更适合当前的情况。