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

不使用pandas如何从CSV文件中将行数据分组为目标列表

不使用Pandas处理CSV生成品牌和车型列表的实现方法

Python自带标准库即可完成需求,无需安装任何第三方依赖,以下是两种可直接运行的实现方案:


方案1:使用内置csv模块(更规范,适配复杂CSV场景)

import csv

# 初始化字典存储品牌和对应车型的映射
brand_model_map = {}

with open("cars.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    for row in reader:
        # 跳过空行、注释行
        if not row or row[0].strip().startswith("#"):
            continue
        brand = row[0].strip()
        model = row[1].strip()
        # 新增品牌或追加对应车型
        if brand not in brand_model_map:
            brand_model_map[brand] = []
        brand_model_map[brand].append(model)

# 转换为要求的输出格式
brands = list(brand_model_map.keys())
models = list(brand_model_map.values())

方案2:直接读取文件解析(无需导入csv模块,适配简单格式CSV)

brand_model_map = {}

with open("cars.csv", "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        # 跳过空行、注释行
        if not line or line.startswith("#"):
            continue
        brand, model = line.split(",")
        brand = brand.strip()
        model = model.strip()
        if brand not in brand_model_map:
            brand_model_map[brand] = []
        brand_model_map[brand].append(model)

brands = list(brand_model_map.keys())
models = list(brand_model_map.values())

输出验证

运行后打印两个变量即可得到目标格式:

print(brands)
print(models)

输出结果:

["Bugatti","VW","Opel"]
[["Veyron","Chiron"], ["Golf","Passat","Polo","Caddy"], ["Insignia"]]

注:Python3.7及以上版本字典默认保留插入顺序,输出顺序和CSV内品牌首次出现的顺序完全一致


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:45:08