在python3中打印学生姓名和学生分数

时间:2019-09-23 13:53:52

标签: python

我想打印学生的姓名和分数,但我有问题

这是代码

from collections import OrderedDict
from operator import itemgetter

A = 'Ali'
AV = 19.75
M = 'Mohammad'
MV = 19.64
C = 'Cacurs'
CV = 19.50

Name_Ave = {C:CV, M:MV, A:AV}
D = OrderedDict(sorted(Name_Ave.items(), key = itemgetter(1)))


for Keys in D.keys():
    for Values in D.values():
        print('%s Average is: %s' %(Keys, Values))

----这里是外面

Cacurs Average is: 19.5
Cacurs Average is: 19.64
Cacurs Average is: 19.75
Mohammad Average is: 19.5
Mohammad Average is: 19.64
Mohammad Average is: 19.75
Ali Average is: 19.5
Ali Average is: 19.64
Ali Average is: 19.75

我该怎么办? 请帮助我

4 个答案:

答案 0 :(得分:1)

A = 'Ali'
AV = 19.75
M = 'Mohammad'
MV = 19.64
C = 'Cacurs'
CV = 19.50

Name_Ave = {C:CV, M:MV, A:AV}
for item in Name_Ave:
    print(item+' score is : '+str(Name_Ave[item]))

答案 1 :(得分:0)

现在,对于D中的每个键,您正在执行的操作是打印字典中的所有值。因此,对于每个学生,您正在遍历字典中所有年级的循环,因此为什么要为每个学生打印每个年级。

应该做的是遍历每个键/值对:

for key, value in D.items():
    print('%s Average is: %s' %(key, value))

答案 2 :(得分:0)

解决方案可以是这样的:

from collections import OrderedDict
from operator import itemgetter

A = 'Ali'
AV = 19.75
M = 'Mohammad'
MV = 19.64
C = 'Cacurs'
CV = 19.50

Name_Ave = {C:CV, M:MV, A:AV}
D = OrderedDict(sorted(Name_Ave.items(), key = itemgetter(1)))


for Keys,Values in zip(D.keys(),D.values()):
        print('%s Average is: %s' %(Keys, Values))

@Daniel Mesejo指出,您可以如下更改for周期:

for key, value in D.items():
        print('%s Average is: %s' %(key,value))

答案 3 :(得分:0)

我想如果要通过对名称进行排序来打印平均分数,可以只使用sorted(Name_Ave.items())。

for (name, average) in sorted(Name_Ave.items()): 
    print("The average of {name} is {average}".format(name=name, average=average))