gpt4 book ai didi

python - 将列表项打印为整数

转载 作者:太空宇宙 更新时间:2023-11-03 16:57:23 25 4
gpt4 key购买 nike

所以我有一些代码可以读取包含这种格式的分数的文件:

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

for name, scores in sorted(data.items()):
highest = scores[-1] #was scores[-1:]
alpha.update({name:highest})
print(alpha)

关于python - 将列表项打印为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35302682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com