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

Python如何按clas为键分组对应name值生成符合要求的字典

问题原因

原有分组逻辑中,每次遍历到对应clas值时,直接通过赋值覆盖了字典中该键的已有值,因此同一clas下只会保留最后遍历到的name,无法完成聚合。

修复方案(仅使用Python内置函数)

方法1:使用字典内置setdefault方法(写法最简)

setdefault会自动判断键是否存在,不存在则设置默认空列表,存在则直接返回已有列表,直接往列表追加元素即可:

# 按clas分组生成字典逻辑(修正后)
dictionary = {}
array = ['x1', 'x2', 'x3', 'x4', 'x5']
for name in array:
    classs = data.get(name)[2]
    dictionary.setdefault(classs, []).append(name)
print(dictionary)

方法2:手动判断键是否存在(逻辑更直观)

如果需要更清晰的判断逻辑,也可以手动校验键是否在字典中:

dictionary = {}
array = ['x1', 'x2', 'x3', 'x4', 'x5']
for name in array:
    classs = data.get(name)[2]
    if classs not in dictionary:
        dictionary[classs] = []
    dictionary[classs].append(name)
print(dictionary)

额外说明

你提供的文件示例是空格分隔字段,但读取代码中用了split(","),如果你的实际sample.csv是逗号分隔可正常运行,如果是和示例一致的空格分隔,把split(",")改为split()即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:15:07