将列表项打印为整数

2024-06-17 04:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一些代码可以读取一个包含以下格式的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)

虽然这样输出的效果更好,但程序并没有按顺序打印出来。我该怎么修?你知道吗


Tags: 代码nameinalphaforyourdatamax
2条回答

使用[-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)

如果需要最高分,那么使用^{}函数

>>> from collections import defaultdict
>>> data = defaultdict(list)
>>> with open('StudentsScoreA.txt') as f:
...     for line in f:
...         name, score = line.split()
...         data[name].append(int(score))
... 
>>> for name, score in data.items():
...     print('{} your score was {}'.format(name, max(score)))
... 
eddie your score was 7
lenard your score was 10
max your score was 5
james your score was 4
zack your score was 3

相关问题 更多 >