我想在python中对dict进行排序。因为我是新人,我不知道我哪里出错了。下面的代码只对前两个条目进行排序。
请咨询
scorecard ={}
result_f = open("results.txt")
for line in result_f:
(name,score) =line.split()
scorecard[score]=name
for each_score in sorted(scorecard.keys(),reverse =True):
print('Surfer ' + scorecard[each_score]+' scored ' + each_score)
result_f.close()
答案 0 :(得分:3)
我的猜测是你将得分保持为字符串而不是整数。字符串的排序方式与整数排序方式不同。考虑:
>>> sorted(['2','10','15'])
['10', '15', '2']
>>> sorted([2, 10, 15])
[2, 10, 15]
旁白:你从得分映射到冲浪者 - 映射应该与此相反。否则你将无法存储两名得分相同的冲浪者。
通过更改来反转映射并将分数作为整数处理:
s = '''Fred 3
John 10
Julie 22
Robert 10
Martha 10
Edwin 9'''
scorecard = {}
for line in s.split('\n'):
name, score = line.split()
scorecard[name] = score
keyfunc = lambda item: (int(item[1]), item[0]) # item[1] is cast to int for sorting
for surfer, score in sorted(scorecard.items(), key=keyfunc, reverse=True):
print '%-8s: %2s' % (surfer, score)
结果:
Julie : 22
Robert : 10
Martha : 10
John : 10
Edwin : 9
Fred : 3
如果您希望按字母顺序排列名字,并按降序排列分数,请将keyfunc
更改为keyfunc = lambda item: (-int(item[1]), item[0])
,并从reverse=True
删除sorted
。
通过这些更改,结果是:
Julie : 22
John : 10
Martha : 10
Robert : 10
Edwin : 9
Fred : 3
答案 1 :(得分:2)
我猜您的输入文件包含
之类的行cory 5
john 3
michael 2
heiko 10
frank 7
在这种情况下,您必须将分数值转换为整数才能正确排序:
scorecard ={}
result_f = open("results.txt")
for line in result_f:
(name,score) =line.split()
scorecard[int(score)]=name
for each_score in sorted(scorecard.keys(),reverse =True):
print('Surfer ' + scorecard[each_score]+' scored ' + str(each_score))
result_f.close()
答案 2 :(得分:1)
如果两个名称可能具有相同的分数,可能只是将记分卡存储为列表:
scorecard = []
with open("results.txt") as result_f:
for line in result_f:
name,score = line.split()
scorecard.append((score,name))
for score,name in sorted(scorecard,reverse =True):
print('Surfer ' + name +' scored ' + str(score))