所以我有一些代码可以读取一个包含以下格式的score的文件:
lenard 1
max 1
lenard 1
max 5
zack 3
max 4
james 4
zack 3
zack 3
james 4
eddie 7
james 4
eddie 7
eddie 7
lenard 4
lenard 10
我有一个代码,它为每个名字取最高的分数,并从高到低输出:
data = {}
alpha={}
with open('StudentsScoreA.txt') as fobj:
for line in fobj: #
name, score = line.split()
data.setdefault(name, []).append(int(score))
for name, scores in sorted(data.items()):
highest = scores[-1:]
alpha.update({name:highest})
print(alpha)
for x in sorted(alpha, key=alpha.get, reverse=True):
print('{} your score was {}'.format(x, alpha[x))
程序正常,但输出不正确:
lenard your score was [10]
eddie your score was [7]
max your score was [4]
james your score was [4]
zack your score was [3]
我在想我该怎么把它打印出来:
lenard your score was 10
我确实试着这样做:
highest = ''.join(str(item) for item in highest)
虽然这样输出的效果更好,但程序并没有按顺序打印出来。我该怎么修?你知道吗
使用[-1]输入[-1:] 切片语法(在列表中)将始终返回一个列表
[1,2,3,4][-1]=>;4
如果需要最高分,那么使用^{} 函数
相关问题 更多 >
编程相关推荐