问题
My dictionary as of now is like this:
class_1 = {'Bob':[9,5,4,3,3,4], 'John':[5,5,7,3,6], 'Andy':[7,5,6,4,5], 'Harris':[3,4,2,3,2,3,2]}
What i am trying to make it look like is this:
class_1_average ={'Bob':[average of scores],'John':[average of scores].........
How can i do this so that even when the scores updates the average also updates with it. And is there also a way to find the highest score out of the scores
回答1:
try like this:
class_1_average = {key: sum(value)/len(value) for key, value in class_1.items()}
For max value: you can use max built-in function over the value of dictionary
max_each = {key: max(value) for key, value in class_1.items()}
回答2:
You can use numpy.mean
in a generator expression to get the average for each student. You can use this paradigm in general to get other statistics.
>>> from numpy import mean
>>> class_1 = {'Bob':[9,5,4,3,3,4], 'John':[5,5,7,3,6], 'Andy':[7,5,6,4,5], 'Harris':[3,4,2,3,2,3,2]}
>>> class_1_average = {name: mean(values) for name, values in class_1.items()}
>>> class_1_average
{'John': 5.2000000000000002, 'Harris': 2.7142857142857144, 'Andy': 5.4000000000000004, 'Bob': 4.666666666666667}
回答3:
One thing that comes to mind if you need to keep your averages updated "in real time" (although is probably killing flies with nuclear weapons and not really what you need) would be creating a custom class that inherits from the builtin dict type and extend it with an averages
method:
import pprint
class MyDict(dict):
def averages(self):
averages = {}
for name, score_list in self.iteritems():
averages[name] = sum(score_list) / len(score_list)
return averages
if __name__ == "__main__":
class_1 = MyDict({
'Bob': [9, 5, 4, 3, 3, 4],
'John': [5, 5, 7, 3, 6],
'Andy': [7, 5, 6, 4, 5],
'Harris': [3, 4, 2, 3, 2, 3, 2]
})
print "class_1: %s" % pprint.pformat(class_1)
print "class_1_averages: %s" % pprint.pformat(class_1.averages())
print "Bob's average: %s" % pprint.pformat(class_1.averages()['Bob'])
print "Setting Bob's scores to [1, 1, 1]"
class_1['Bob'] = [1, 1, 1]
print "Bob's average: %s" % pprint.pformat(class_1.averages()['Bob'])
That outputs:
class_1: {'Andy': [7, 5, 6, 4, 5],
'Bob': [9, 5, 4, 3, 3, 4],
'Harris': [3, 4, 2, 3, 2, 3, 2],
'John': [5, 5, 7, 3, 6]}
class_1_averages: {'Andy': 5, 'Bob': 4, 'Harris': 2, 'John': 5}
Bob's average: 4
Setting Bob's scores to [1, 1, 1]
Bob's average: 1
Maybe you can use this as an idea of what Python allows you to do (which doesn't necessarily mean that you should be doing it this way) You're probably much better off with Hackaholic's answer.
来源:https://stackoverflow.com/questions/28592580/working-out-an-average-of-the-values-in-a-dictionary