【发布时间】:2015-01-27 21:43:54
【问题描述】:
txt 将包含这样的内容:
Matt Scored: 10
Jimmy Scored: 3
James Scored: 9
Jimmy Scored: 8
....
到目前为止我的代码:
from collections import OrderedDict
#opens the class file in order to create a dictionary
dictionary = {}
#splits the data so the name is the key while the score is the value
f = open('ClassA.txt', 'r')
d = {}
for line in f:
firstpart, secondpart = line.strip().split(':')
dictionary[firstpart.strip()] = secondpart.strip()
columns = line.split(": ")
letters = columns[0]
numbers = columns[1].strip()
if d.get(letters):
d[letters].append(numbers)
else:
d[letters] = list(numbers)
#sorts the dictionary so it has a alphabetical order
sorted_dict = OrderedDict(
sorted((key, list(sorted(vals, reverse=True)))
for key, vals in d.items()))
print (sorted_dict)
此代码已生成按字母顺序排序的名称输出,其分数从最高到最低打印。但是,现在我需要能够以最高分在前、最低分在后的方式输出排序的名称。我尝试使用 max 函数,但是它只输出名称而不是分数本身,而且我希望输出只有最高分,而不是像我当前代码那样的以前的分数。
【问题讨论】:
-
使用
itertools.groupby应该相当容易。让我做点什么 -
@user3809875 不,你误解了这个问题
标签: python sorting dictionary