如何用Python从CSV文件中筛选并打印最高分数对应帖子标题
修正Python代码以获取Reddit帖子最高分对应标题
需求:从reddit_vm.csv文件中找出最高分数对应的帖子标题并打印,目标标题为I would rage if this was handed to me...,预期输出格式如下:
Title for the Highest Scores: I would rage if this was handed to me...
原代码存在的问题
- 直接调用
max(score)但未定义score变量,需先从数据中提取分数列表 - 用
title(score == highScore)筛选标题是错误语法,无法实现分数与标题的对应匹配 - 打印语句中的换行写法错误,会导致语法异常
analyze函数无返回值,avgScore赋值没有实际作用
修正后的代码
import csv def analyze(entries): print(f'first entry: {entries[0]}') with open("reddit_vm.csv", "r", encoding='UTF-8', errors="ignore") as input: entries = [(e['id'], int(e['score']), int(e['comms_num']), e['title']) for e in csv.DictReader(input)] analyze(entries) # 提取所有帖子的分数 scores = [entry[1] for entry in entries] high_score = max(scores) print("\nHighest score:") print(high_score) # 筛选出所有分数等于最高分的标题 high_titles = [entry[3] for entry in entries if entry[1] == high_score] print("\nTitle for the Highest Scores:") for title in high_titles: print(title)
修正说明
- 新增
scores列表推导式,从entries中提取所有分数,解决max()参数未定义的问题 - 用带条件的列表推导式
high_titles直接匹配分数与标题,避免单独提取标题后无法对应分数的问题 - 修正换行符为
\n,保证打印格式正确 - 遍历打印所有最高分标题,兼容存在多个同分帖子的情况
内容的提问来源于stack exchange,提问作者han zo
相关产品推荐
相关产品推荐

