You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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)

修正说明

  1. 新增scores列表推导式,从entries中提取所有分数,解决max()参数未定义的问题
  2. 用带条件的列表推导式high_titles直接匹配分数与标题,避免单独提取标题后无法对应分数的问题
  3. 修正换行符为\n,保证打印格式正确
  4. 遍历打印所有最高分标题,兼容存在多个同分帖子的情况

内容的提问来源于stack exchange,提问作者han zo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:40:18