用双数字排序问题

时间:2015-02-21 19:26:20

标签: python sorting

这段代码存在问题。它是这样编写的,它按字母顺序和人的最高分输出分数。分数存储在文本文件中,如下所示:

Tom,3
South,5
James,0
Tom,0
Tom,7
South,0
South,7
James,5
James,10

我使用的程序如下:

def alpha1():
    with open('class1.txt', 'r') as f:
        values = f.read().split()
        scores = {}
        for item in values:
            item = item.split(',')
            if item[0] in scores.keys():
                scores[item[0]].append(item[1])
            else:
                scores[item[0]] = [item[1]]
    high_scores = [[key, max(scores[key])] for key in scores.keys()]
    high_scores.sort()

    for item in high_scores:
        print ("{}: {}".format(item[0], item[1]))

它输出的所有内容都是正确的,除非文本文件中有人得到的最高得分为10.它输出第二高分,例如,詹姆斯得分为10.它将输出詹姆斯,但输出詹姆斯'第二高分,这是5.为什么这样做?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

from collections import defaultdict
import csv


d = defaultdict(list)

with open('class1.txt') as f:
    # split on , so Tom,3 -> ['Tom', '3']
    r = csv.reader(f,delimiter=",")
    for row in r:
        # cast score to int and append to list
        d[row[0]].append(int(row[1]))

# sort by name and get max of each scores/values
for k,v in sorted(d.items()):
    print ("{}: {}".format(k, max(v)))

James: 10
South: 7
Tom: 7

如果密钥不存在,则collections.defaultdict将添加密钥,否则只需追加该值。