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

如何用Python将CSV按指定列分组为字典(键为位置,值为球员列表)

按位置分组CSV球员数据的解决方案

原始CSV数据

jersey number,   position,   name,   birth_date,    birth_city,   years_in_nba,   team
23           ,     SF    ,   Lebron,  12/30/84 ,     Akron    ,      19      ,   Lakers
30           ,     PG    ,   Curry,   03/14/88 ,     Akron    ,      13      ,   Warriors
34           ,     PF    ,   Giannis, 08/26/89 ,     Athens    ,      8      ,   Bucks

预期目标

生成键为球员位置、值为对应球员信息列表的字典,格式示例:

{
"SF": [{"jersey number": "23", "position": "SF", ...}, ...],
"PG": [{"jersey number": "30", "position": "PG", ...}, ...],
"PF": [{"jersey number": "34", "position": "PF", ...}, ...]
}

原代码问题

你的代码直接将row赋值给positions[row["position"]],导致同位置的新球员会覆盖旧球员数据,无法实现列表追加的需求。

修改后的代码

from csv import DictReader

def players_position(filename):
    positions = {}
    with open(filename, 'r') as file_obj:
        dict_reader = DictReader(file_obj, delimiter=",")
        # 清理字段名中的多余空格,避免键名带空格
        cleaned_fieldnames = [name.strip() for name in dict_reader.fieldnames]
        dict_reader.fieldnames = cleaned_fieldnames
        
        for row in dict_reader:
            # 清理每行数据值的多余空格
            cleaned_row = {key: value.strip() for key, value in row.items()}
            pos = cleaned_row["position"]
            # 若位置未在字典中,先创建空列表
            if pos not in positions:
                positions[pos] = []
            # 将当前球员信息追加到对应位置的列表
            positions[pos].append(cleaned_row)
    return positions

# 调用示例,替换为你的CSV文件名
print(players_position("players.csv"))

关键修改说明

  • 将positions字典移到函数内部,避免全局变量带来的副作用
  • 处理CSV字段名和数据值中的多余空格(原始CSV存在大量空格,不处理会导致键名或值格式混乱)
  • 遍历每行数据时,先检查当前位置是否已存在于字典:
    • 不存在则创建空列表
    • 存在则将清理后的球员数据追加到对应列表中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:43:00