如何解决Python合并CSV/TSV数据时的list index out of range错误?
解决"list index out of range"错误的方案
错误原因
你在main函数里直接访问index[3],但只有当国家在happy_dict中存在时,才会给line追加第4个元素(幸福值)。如果某个国家不在字典里,line的长度还是3,此时访问索引3就会触发列表索引越界错误。
修正方案
方案1:只输出有幸福值的行
在read_gdp_data里,仅当happiness不为None时,才将line加入Data,确保后续main中所有行都有4个元素:
import csv def make_happy_dict(): filename = 'happiness.csv' happy_dict = {} with open(filename, "r") as infile: next(infile) # 用next跳过表头,比readline更规范 happy_csv = csv.reader(infile) for row in happy_csv: # 增加行长度判断,避免csv行格式错误 if len(row) >= 3: happy_dict[row[0].strip()] = row[2] return happy_dict def read_gdp_data(): Data = [] # 用with语句管理TSV文件,自动关闭资源 with open("world_pop_gdp.tsv", 'r') as countries: # 用csv.reader处理TSV,指定分隔符为\t,避免手动split的格式问题 tsv_reader = csv.reader(countries, delimiter='\t') next(tsv_reader) # 若TSV有表头则跳过,无表头可注释此行 happy_dict = make_happy_dict() for line in tsv_reader: if len(line) < 3: continue # 跳过格式不完整的行 country = line[0].strip() # 处理人口数据 line[1] = line[1].replace(",", "") # 处理GDP数据 gdp = line[2].replace('$', "").replace(',', "").strip() line[2] = gdp happiness = happy_dict.get(country) if happiness is not None: line.append(happiness) Data.append(line) return Data def main(): GDP = read_gdp_data() for index in GDP: print(f"{index[0]},{index[1]},{index[2]},{index[3]}") main()
方案2:给无幸福值的行填充默认值
如果需要保留所有国家的行,给不存在幸福值的行填充"N/A"这类默认值:
修改read_gdp_data中的核心逻辑:
# 用get的默认值参数,不存在时返回"N/A" happiness = happy_dict.get(country, "N/A") line.append(happiness) Data.append(line)
这样所有行都会有4个元素,main中访问index[3]就不会报错。
额外优化点
- 用
next(infile)代替infile.readline()跳过表头,符合csv模块的标准用法 - 用
csv.reader处理TSV文件(指定delimiter='\t'),避免手动split("\t")可能出现的格式异常 - 用
with语句管理文件,自动关闭文件句柄,避免资源泄漏 - 增加行长度判断,跳过格式错误的行,提前规避索引越界风险
内容的提问来源于stack exchange,提问作者Fora Gamsonly
相关产品推荐
相关产品推荐

