Finding mean of a values in a dictionary without using .values() etc

前端 未结 10 1303
挽巷
挽巷 2021-01-02 17:29

I have a dictionary that looks like:

G={\'E\': 18.0, \'D\': 17.0, \'C\': 19.0, \'B\': 15.0, \'A\': 0}

I have to find the mean of the values

10条回答
  •  说谎
    说谎 (楼主)
    2021-01-02 17:46

    To do this with a "simple for loop", using your constraints against using the dict methods:

    G = {'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}
    
    
    count = 0
    _sum = 0
    for key in G:
        count += 1
        _sum += G[key]
    
    print('this is the mean: ', _sum/count)
    

    If you're supposed to avoid dict methods, clearly this is an academic exercise.

    Without that constraint:

    The statistics module in the standard library has a mean method, which would be my first thought (as the standard library does not require third party packages.):

    >>> G={'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}
    >>> from statistics import mean
    >>> mean(G[k] for k in G)
    13.8
    

    Third party packages like numpy and pandas have objects with a mean method:

    >>> from numpy import array
    >>> array([G[k] for k in G]).mean()
    13.8
    
    >>> from pandas import Series
    >>> Series([G[k] for k in G]).mean()
    13.8
    

    If we allow ourselves to use the values() method, this gets a little simpler with iterable unpacking. For some reason the other answers violate that condition, so I figure I should show the more efficient way of doing it:

    >>> Series([*G.values()]).mean()
    13.8
    

提交回复
热议问题