You need to enable JavaScript to run this app. 如何对嵌套字典topic_emb[topic][word]中词嵌入向量各维度求和
优惠活动
大模型
产品
解决方案
定价
更多

如何对嵌套字典topic_emb[topic][word]中词嵌入向量各维度求和

实现代码

你可以用Python内置的sum()函数配合嵌套字典推导快速完成转换,处理逻辑如下:

示例输入

# 输入嵌套字典示例
topic_emb = {0: {'sky': [0.229, 0.113, 0.445]}}

简洁版实现(字典推导式)

result = {
    topic: {word: sum(emb) for word, emb in word_map.items()}
    for topic, word_map in topic_emb.items()
}

执行后打印result即可得到预期输出结构:{0: {'sky': 0.787}}

循环版实现(便于调试扩展)

如果需要后续调整计算逻辑,也可以用显式循环写法:

result = {}
for topic, word_map in topic_emb.items():
    result[topic] = {}
    for word, emb in word_map.items():
        # 若需要固定保留n位小数,可以改为 round(sum(emb), 3)
        result[topic][word] = sum(emb)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 06:24:03