[英]Sorting a dict in Python
我想在python中對字典進行排序。 由於我是新手,所以我不知道我要去哪里。 以下代碼僅對前兩個條目進行排序。
請咨詢
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()
我的猜測是您將分數保留為字符串而不是整數。 字符串的排序方式與整數不同。 考慮:
>>> 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
我猜你的輸入文件包含如下行
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()
如果兩個名字的分數相同,則可以將記分卡存儲為列表:
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.