我正在研究以下内容,我创建了一个字典对象,如下所示,我需要定义3个不同的函数。 maxScore的函数,minScore的函数,平均函数以及打印全部3。
我的字典对象代码如下
scores = {}
scores['Andy'] = 78
scores['Bill'] = 82
scores['Cindy'] = 94
scores['Dave'] = 77
scores['Emily'] = 82
scores['Frank'] = 94
scores['Gene'] = 87
我似乎无法正确定义函数来打印结果。
答案 0 :(得分:3)
使用min()
和max
:
>>> scores = {}
>>> scores['Andy'] = 78
>>> scores['Bill'] = 82
>>> scores['Cindy'] = 94
>>> scores['Dave'] = 77
>>> scores['Emily'] = 82
>>> scores['Frank'] = 94
>>> scores['Gene'] = 87
>>> max(scores, key=scores.get)
'Frank'
>>> min(scores, key=scores.get)
'Dave'
和平均值:
>>> sum(scores[i] for i in scores)/len(scores)
84
答案 1 :(得分:1)
最多:
def max_val(scores):
return max(scores.values())
min
def min_val(scores):
return min(scores.values())
和avg
def avg_val(scores):
return sum(scores.values())/len(scores)
答案 2 :(得分:0)
最高得分:
def maxScore(scDict):
max = scDict[0]
for i in scDict:
if scDict[i]>max:
max=scDict[i]
return max
最低分数:
def minScore(scDict):
min = scDict[0]
for i in scDict:
if scDict[i]<max:
min=scDict[i]
return min
平均得分:
def avgScore(scDict):
avg = 0. # python 2
for i in scDict:
avg+=scDict[i]
return avg/len(scDict)
如果您愿意,也可以在minScore(Py 3.0)的情况下使用sys.maxsize
之类的内容。
答案 3 :(得分:0)
试试这个:
best_scores = sorted(scores, key=scores.get, reverse=True)
maxScore = scores[best_scores[0]]
minScore = scores[best_scores[-1]]
average = sum(scores.values())/len(scores.values())
答案 4 :(得分:0)
sorted(scores.items(), cmp=lambda x, y: x[1] - y[1])