我需要知道如何根据aveage分数对python字典进行排序,学生的分数有多重?
我班上有许多参加测验的学生的名字。ome做了不止一次,我想用python计算出平均值。我把分数保存在一个文本文件中,但我不知道如何编程,所以它会按总分数除以他们参加考试的次数来排序。我正在使用python 3.4.1我需要知道如何根据aveage分数对python字典进行排序,学生的分数有多重?,python,sorting,dictionary,average,Python,Sorting,Dictionary,Average,我班上有许多参加测验的学生的名字。ome做了不止一次,我想用python计算出平均值。我把分数保存在一个文本文件中,但我不知道如何编程,所以它会按总分数除以他们参加考试的次数来排序。我正在使用python 3.4.1 the text file looks like this : zor:10 zor:21 bob:30 qwerty:46 我试着用这个来分类: if schClass == '2': schClass = open("scores2.txt", 'r')
the text file looks like this :
zor:10
zor:21
bob:30
qwerty:46
我试着用这个来分类:
if schClass == '2':
schClass = open("scores2.txt", 'r')
li = open("scores2.txt", 'r')
data = li.read().splitlines()
for li in data:
name = li.split(":")[0]
score = li.split(":")[1]
if name not in diction1:
diction1[name] = score
elif name in diction1 :
diction1[name] = (score) + (diction1[name])
for name in diction1:
diction1[name] = int(diction1[name])/3
您可以使词典具有以下结构:
diction1 = {'zor': [10, 21,], 'bob': [30]}
然后创建一个新词典,在其中存储名称和平均分数:
averages_dct = {'zor': 15.5, }
您的代码应该如下所示:
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
这段代码背后的思想如下:在dataload方法中,python从文本文件(字符串或其他地方)读取考试,并将其放入字典中,其中的值是考试评估列表。而在printdictionary方法中,计算平均分数并将结果显示给用户 代码是做什么的?我认为你的字典应该是
{“name”:[score1,score2,score3]}
的形式,你应该首先加载字典中的所有分数,完成后,循环所有名称以报告平均值。只需打印普通文本文件而不计算平均值。不可能是这样,因为不同的程序会生成这样的名称和分数,