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

如何合并两个字典,对同键数组值求和后计算平均值?

问题背景

我有两个字典,键一一对应,值为包含numpy数组的列表,示例如下:

print(helix1_coords)
# 输出:
{'A-85-CA': [array([ 50.393, -20.181,  12.316], dtype=float32)], 'A-86-CA': [array([ 52.819, -18.757,  14.976], dtype=float32)]...}

print(helix2_coords)
# 输出:
{'A-85-CA': [array([ 31.465,  -1.023, -23.405], dtype=float32)], 'A-86-CA': [array([ 29.751,  -2.69 , -26.312], dtype=float32)]...}
需求
  1. 合并两个字典生成avg_coords,键与helix1_coords完全一致,值为对应键下两个数组的元素逐个相加,示例结果:
print(avg_coords)
# 输出:
{'A-85-CA': [array([ 81.858, -21.204,  -11.089], dtype=float32)], 'A-86-CA': [array([ 82.57, -21.447,  -11.336], dtype=float32)]...}
  1. 再将每个值中的数组元素除以2,最终结果:
print(avg_coords)
# 输出:
{'A-85-CA': [array([ 40.929, -10.602,  -5.5445], dtype=float32)], 'A-86-CA': [array([ 41.285, -10.7235,  -5.668], dtype=float32)]...}
尝试过的方法及问题
  • 方法1:
avg_coords = {key: np.add(helix1_coords.values(), helix2_coords.values()) for key in helix1_coords}

问题:生成的字典所有值完全相同,等于helix1_coords的最后一个值。

  • 方法2:
avg_coords = {key: np.concatenate((helix1_coords.get(key, np.array([])), helix2_coords.get(key, np.array([])))) for key in set(helix1_coords.keys()).union(set(helix2_coords.keys()))}

问题:抛出错误 ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)


解决方案

直接遍历helix1_coords的每个键,取出对应两个字典中的数组(注意值是列表嵌套数组,需取列表第一个元素),完成元素级相加后除以2,再保持列表格式存入新字典即可:

基础循环写法

import numpy as np

avg_coords = {}
for key in helix1_coords:
    arr1 = helix1_coords[key][0]
    arr2 = helix2_coords[key][0]
    avg_arr = (arr1 + arr2) / 2
    avg_coords[key] = [avg_arr]

字典推导式简化写法

avg_coords = {
    key: [(helix1_coords[key][0] + helix2_coords[key][0]) / 2]
    for key in helix1_coords
}

错误原因分析

  • 方法1中,helix1_coords.values()返回的是所有值的集合视图,np.add会将两个视图整体做广播运算,而非逐个键对应相加,导致结果全部重复。
  • 方法2使用的np.concatenate是数组拼接函数,并非元素级运算;再加上你的值是列表嵌套数组,传入函数时维度不匹配,因此报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:50:22