diction1 = {'john': [10, 20], 'mary': [12,], 'chris': [10, 20]}
# Contains names as keys and average as values.
averages_dct = {}
for name in diction1:
student_average = sum(diction1[name]) / len(diction1[name])
# Store the value:
averages_dct.update({name: student_average})
# Dict containing averages as keys and names as values
# (inserting averages first)
reversed_dct = {averages_dct[k]: [] for k in averages_dct}
# (matching names)
for average in reversed_dct:
for name in averages_dct:
if average == averages_dct[name]:
# Adds name of student if he has this average
reversed_dct[average].append(name)
# Prints the results from highest to lowest.
for av in sorted(reversed_dct, reverse=True):
print('average: %s, students: %s' % (av, reversed_dct[av]))
def dataload():
#This is just to load your data into a custom dictionary, for simplicity
#i wrote example data into a string, you can use your I/O logic
test="zor:10\n\
zor:21\n\
bob:30\n\
qwerty:46\n\
zor:24"
dictionary = {}
d = test.splitlines()
for i in d:
values = i.split(':')
name = values[0]
score = float(values[1])
if name not in dictionary:
dictionary[name] = [score]
else:
l = dictionary[name]
l.append(score)
dictionary[name] = l
return dictionary
def printdictionary(d):
#This is shows the content of your custom dictionary
for item in d.keys():
l = d[item]
avg = 0
for exam in l:
avg = avg + exam
avg = avg / len(l)
print(item," => ", d[item]," => ", avg)
dictionary = dataload()
printdictionary(dictionary)
# output:
#bob => [30.0] => 30.0
#zor => [10.0, 21.0, 24.0] => 18.333333333333332
#qwerty => [46.0] => 46.0
您可以使字典具有以下结构:
然后创建一个新字典,在其中存储姓名和平均分数:
^{pr2}$您的代码应该如下所示:
这对你有帮助吗?在
这段代码背后的思想如下:在dataload方法中,python从textfile(字符串或其他地方)读取考试,并将它们放入字典中,其中value是考试评估的列表。在printdiction方法中,计算平均分并将结果显示给用户。在
相关问题 更多 >
编程相关推荐