Python 3.x: Merge two dictionaries with same keys and values being array

后端 未结 4 1321
遥遥无期
遥遥无期 2021-01-20 12:13

Python version: 3.x

I have two dictionaries with same keys and the values are arrays. Most of the questions I saw here, for the required purpose, have only one value

4条回答
  •  滥情空心
    2021-01-20 12:28

    import numpy as np
    
    d1 = {(1, "Autumn"): [2.5, 4.5, 7.5, 9.5], (1, "Spring"): [10.5, 11.7, 12.3, 15.0]}
    d2 = {(1, "Autumn"): [10.2, 13.3, 15.7, 18.8], (1, "Spring"): [15.6, 20, 23, 27]}
    d3 = {(1, "Autumn"): np.array(d1[(1, "Autumn")] + d2[(1, "Autumn")]), (1,"Spring"): np.array(d1[(1, "Spring")] + d2[(1, "Spring")])}
    

    I used the np.array() in the end because there is difference between lists and numpy arrays. When you use the A + B in numpy, each element of the A added to the array other element of the B. On the other hand, when use A+B where A and B are lists, they join each other.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题