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

如何用for循环将CSV列存入列表?解决输出异常及字符串处理需求

CSV数据读取与处理优化方案

代码作者:Abdulmalik

原代码

import csv

def loadCSVData(filename):
    list = [] #list for storing file content
    with open(filename, newline='') as file:# 
        fileContent = csv.DictReader(file)
        for line in fileContent:
            list.append(line['Score'])
            print(list)
        fileContent.close()
    return list

预期输出

['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7', '90.4', '90.1', '89.8', '89.5', '89.2', '89', '88.8', '88.6', '88.4', '88.2', '88', '87.8', '87.6', '87.5', '87.3', '87.2', '87', '86.9', '86.8', '86.6', '86.5', '86.4', '86.3', '86.1', '86', '85.9', '85.8', '85.7', '85.6', '85.5', '85.4', '85.3', '85.2', '85.1', '85', '85', '84.9', '84.8', '84.7', '84.6', '84.5', '84.5', '84.4', '84.3', '84.2', '84.2', '84.1', '84', '84', '83.9', '83.8', '83.8', '83.7', '83.6', '83.6', '83.5', '83.4', '83.4', '83.3', '83.3', '83.2', '83.1', '83.1', '83', '83', '82.9', '82.9', '82.8', '82.8', '82.7', '82.6', '82.6', '82.5', '82.5', '82.4', '82.4', '82.3', '82.3', '82.2', '82.2', '82.2', '82.1', '82.1', '82', '82', '81.9', '81.9', '81.8', '81.8', '81.8']

实际输出(部分)

['100']
['100', '96.7']
['100', '96.7', '95.1']
['100', '96.7', '95.1', '94.1']
['100', '96.7', '95.1', '94.1', '93.3']
['100', '96.7', '95.1', '94.1', '93.3', '92.6']
['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92']
['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5']
['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1']
['100', '96.7', '95.1', '94.1', '93.3', '92.6', '92', '91.5', '91.1', '90.7']
# 后续内容省略

需求说明

  • 仅打印最终的完整列表,而非每次追加后的列表
  • 对读取到的Score列数据执行strip()和split(',')操作,提供基于列表的实现方案

修改后的代码

import csv

def loadCSVData(filename):
    score_list = []  # 避免使用内置类型名`list`作为变量名
    with open(filename, newline='') as file:
        file_reader = csv.DictReader(file)
        for row in file_reader:
            # 处理Score字段:先去除前后空白,再按逗号分割
            processed_scores = row['Score'].strip().split(',')
            # 将分割后的分数逐个添加到列表中
            score_list.extend(processed_scores)
    
    # 循环结束后打印最终完整列表
    print(score_list)
    return score_list

关键修改点

  1. 解决多次打印问题:将print()语句移出循环,放在所有数据处理完成后,确保只打印最终的完整列表。
  2. 实现字段处理:对每个Score字段先执行strip()去除前后空白字符,再用split(',')按逗号分割成多个元素,最后用extend()将这些元素批量添加到主列表中(如果单个单元格内是逗号分隔的多个分数,会被拆分成独立元素存入列表)。
  3. 代码规范优化:将变量名从list改为score_list,避免覆盖Python内置的list类型;同时移除了手动关闭文件的代码,因为with语句会自动管理文件资源的释放。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:55:39