用python把相同名称的放在一起_分类时把名字和分数放在一起

您可以复制dict,找到最大值,将键保存到列表中,从dict中删除键,然后再这样做,直到复制的dict为空。在import copy

scores = {'hawks': 23, 'eagles': 42, 'knights': 33, 'rabbits': 44} #this or read from .txt

scorescopy = copy.deepcopy(scores) #makes a copy of the dict, so you don't change the dict when deleting keys from the copy

rank = [] #the list in which we want the keys ranked by value

def keywithmaxval(scores): #finde the key with the highest value (stolen from another stackoverflow question)

values = list(scores.values())

keys = list(scores.keys())

return keys[values.index(max(values))]

while len(scorescopy) > 0: #repeats until copy of dict is empty

maxkey = keywithmaxval(scorescopy)

scorescopy.pop(maxkey) #deletes key from copy of dict

rank.append(maxkey) #puts key in the ranked list

print 'rank', rank #list of keys ranked by value

print 'copy of dict', scorescopy #copy of dict, should be empty after we looped trough

print 'original dict',scores #original dict, should be unchanged

print '\nRank:'

for key in rank: print key,':',scores[key] #pretty list of keys and vals

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值