简体   繁体   中英

Need to sort a dictionary by average of nested list of values

dict = {a:[2,4,5],b:[4,6,7],c:[3,1,1]}

Above is an example of a dictionary I have. The length of the nested lists will always be 3 (due to other blocks of code). I have figured out how to sort alphabetically and by highest value of the list inside the dictionary. I am struggling to find a way to calculate the highest AVERAGE score. Below is the desired output:

>>> get_average(dict)
>>> b : 5.66
>>> a : 3.66
>>> c : 1.66

Any tips or even a solution? I'm pretty sure the most efficient way is to use lambda. Can I modify this code to get the average:

sorted(dict.items(), key=operator.itemgetter(1))

First, build a map of the averages using a dict comprehension:

>>> d = {'a':[2,4,5], 'b':[4,6,7], 'c':[3,1,1]}
>>> def mean(L):
        return float(sum(L))/len(L)
... 
>>> d_avg = {k: mean(v) for k, v in d.items()}
>>> d_avg
{'a': 3.6666666666666665, 'b': 5.666666666666667, 'c': 1.6666666666666667}

Then you can sort that by value:

>>> sorted(d_avg, key=d_avg.get, reverse=True)
['b', 'a', 'c']

try this:

 d = {'a':[2,4,5], 'b':[4,6,7], 'c':[3,1,1]}
 sort = sorted(d, key=lambda k: sum(d[k]) / 3, reverse=True)
 for i in sort:
     print(i, ":", sum(d[i]) / 3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM