How can I calculate average of different values in each key of python dictionary?

后端 未结 3 478
余生分开走
余生分开走 2021-01-28 17:17

I have a dictionary. I want to calculate average of values for each key and print result so that the result shows key and associated average. The following code calculates mean

3条回答
  •  迷失自我
    2021-01-28 17:58

    Update for Python 3.4+

    >>> from statistics import mean    # Python 3.4+
    >>> d = {22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]}
    >>> {k:mean(v) for k,v in d.items()}
    {22: 0.5, 23: 0.8, 24: 1.8}
    >>>
    

提交回复
热议问题