将列表项打印为整数

时间:2016-02-09 21:37:01

标签: python list python-3.x

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

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)

虽然这确实输出得更好,但程序不会按排序顺序打印出来。我该如何解决?

2 个答案:

答案 0 :(得分:1)

使用[-1] intead of [-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)

答案 1 :(得分:0)

如果您需要最高分,请使用max功能

>>> 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