Python Lambda函数排序CSV游戏高分列表时触发索引越界错误
解决Python Lambda处理高分CSV时的索引越界问题
嘿,我来帮你搞定这个困扰你的索引越界错误!先看你给出的运行输出:[[], ['Kyle', 40, '03/23/2018'], ['Kyle', 41, '03/23/2018'], ['Kyle', 292, '03/23/2018']],这里面第一个元素是空列表[]——这就是问题的根源!
当你尝试用Lambda函数按**第2项(索引1,Python是0起始)**排序时,这个空列表根本没有索引1的元素,自然就会抛出IndexError。
问题原因拆解
- 初始为空的CSV文件被读取后,可能会生成一个空行(也就是空列表
[]) - 你的代码没有过滤这些无效的空行,导致后续排序时访问不存在的索引
- 另外可能存在的隐患:如果CSV里的分数是字符串类型,排序时会出现逻辑错误(比如
'100'会被认为比'99'小)
修正后的完整解决方案
下面是修复后的代码,我加了详细的注释,帮你理清每个步骤:
import csv from datetime import datetime def handle_high_scores(): current_scores = [] # 1. 读取CSV并清理数据 try: with open('eggs.csv', 'r', newline='', encoding='utf-8') as f: reader = csv.reader(f) # 过滤空行+格式不正确的行,同时把分数转成整数 current_scores = [ [row[0], int(row[1]), row[2]] for row in reader if row and len(row) == 3 # 确保每行有3个有效元素 ] except FileNotFoundError: # 如果文件还不存在,初始化空列表 current_scores = [] # 2. 不足3行时追加测试数据 if len(current_scores) < 3: test_records = [ ['Kyle', 40, '03/23/2018'], ['Kyle', 41, '03/23/2018'], ['Kyle', 292, '03/23/2018'] ] current_scores.extend(test_records) # 3. 模拟玩家的新高分(替换成你的硬编码值) new_high_score = ['Alice', 300, datetime.now().strftime('%m/%d/%Y')] # 4. 处理高分更新逻辑 if len(current_scores) >= 7: # 按分数降序排序(Lambda函数安全访问x[1],因为已经过滤了无效行) sorted_scores = sorted(current_scores, key=lambda x: x[1], reverse=True) # 比较新分数和当前最低的高分 if new_high_score[1] > sorted_scores[-1][1]: sorted_scores.pop() # 移除最低分 sorted_scores.append(new_high_score) current_scores = sorted_scores else: # 不足7行直接追加新记录 current_scores.append(new_high_score) # 5. 最后统一按分数降序排序 current_scores = sorted(current_scores, key=lambda x: x[1], reverse=True) # 6. 写回CSV文件 with open('eggs.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) writer.writerows(current_scores) return current_scores # 运行函数并打印结果 print(handle_high_scores())
关键修复点
- 过滤无效行:读取CSV时,用列表推导式过滤掉空行和元素数量不对的行,确保每个元素都是
[用户名, 分数, 日期]的完整格式 - 类型转换:把分数从字符串转成整数,避免字符串排序的逻辑错误
- 异常处理:捕获文件不存在的情况,初始化空列表,避免首次运行报错
- 安全排序:因为提前过滤了无效行,Lambda函数访问
x[1]时不会再出现索引越界
内容的提问来源于stack exchange,提问作者user9542650
相关产品推荐
相关产品推荐

