Python脚本仅输出Top10最高分,如何修正以同时输出最低分?
问题描述
我生成了两个分别按分数降序、升序排序的列表,希望将Top10最高分和Top10最低分同时打印并写入同一个文本文件。当前我的Python脚本如下:
###ordering them after 10 highest and 10 lowest with open("scoresextreme.txt", "w") as f: sorted_score = sorted(Scores_extreme, key=lambda x: x[1], reverse=True) sorted_score_1 = sorted(Scores_extreme, key=lambda x: x[1], reverse=False) print("Top 10 highest scores") for item1, item2 in sorted_score[:10]: print(f'{item1} \t {item2}') line = ' '.join(str(x) for x in ({item1}, {item2})) f.write(line + '\n') print("Top 10 lowest scores") for item3, item4 in sorted_score_1[:10]: print(f'{item3} \t {item4}') line = ' '.join(str(x) for x in ({item3}, {item4})) f.write(line + '\n') f.close()
但实际运行后,脚本仅打印并写入了Top10最高分,Top10最低分未输出到控制台和文件中,请问该如何修正?
解决方案
问题原因
你的代码存在两个核心问题:
- 手动关闭文件导致后续写入失败:使用
with open(...) as f上下文管理器时,代码块结束后文件会自动关闭。你在代码末尾额外调用了f.close(),这会导致在处理最低分部分时,文件已经被提前关闭,无法写入内容,甚至可能触发异常。 - 集合拼接导致内容无序:
{item1}, {item2}创建的是无序集合,写入文件时可能会打乱名称和分数的顺序,应该改用有序的列表[item1, item2]。
修正后的代码
###ordering them after 10 highest and 10 lowest with open("scoresextreme.txt", "w") as f: sorted_score = sorted(Scores_extreme, key=lambda x: x[1], reverse=True) sorted_score_1 = sorted(Scores_extreme, key=lambda x: x[1], reverse=False) # 输出并写入Top10最高分 print("Top 10 highest scores") for name, score in sorted_score[:10]: print(f'{name} \t {score}') line = ' '.join(str(x) for x in [name, score]) f.write(line + '\n') # 输出并写入Top10最低分 print("\nTop 10 lowest scores") for name, score in sorted_score_1[:10]: print(f'{name} \t {score}') line = ' '.join(str(x) for x in [name, score]) f.write(line + '\n')
额外优化
可以减少一次排序操作提升效率:只做一次降序排序,前10个是最高分,后10个反转后就是升序的最低分:
###ordering them after 10 highest and 10 lowest with open("scoresextreme.txt", "w") as f: # 仅执行一次降序排序 sorted_desc = sorted(Scores_extreme, key=lambda x: x[1], reverse=True) top_high = sorted_desc[:10] # 取后10个并反转得到升序的最低分列表 top_low = sorted_desc[-10:][::-1] print("Top 10 highest scores") for name, score in top_high: print(f'{name} \t {score}') f.write(f"{name} {score}\n") print("\nTop 10 lowest scores") for name, score in top_low: print(f'{name} \t {score}') f.write(f"{name} {score}\n")
内容的提问来源于stack exchange,提问作者Christina H Christiansen
相关产品推荐
相关产品推荐

