如何从最高到最低对字典值进行排序?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从最高到最低对字典值进行排序?相关的知识,希望对你有一定的参考价值。
我的问题是我如何根据最高得分撤回获胜者?因为你不能在字典中排序我用列表尝试了这个,但是然后名字不会出现,只有得分......
a = {'name_a':0}
b = {'name_b':0}
c = {'name_c':0}
d = {'name_d':0}
e = {'name_e':0}
print("Each time someone scores a point, the letter of his name is typed in lowercase. If someone loses a point, the letter of his name is typed in uppercase")
score = input('Enter series of charachters indicating who scored a poitn: ')
for i in score:
if i == 'a':
a['name_a'] += 1
if i == 'A':
a['name_a'] -= 1
if i == 'b':
b['name_b'] += 1
if i == 'B':
b['name_b'] -= 1
if i == 'c':
c['name_c'] += 1
if i == 'C':
c['name_c'] -= 1
if i == 'd':
d['name_d'] += 1
if i == 'D':
d['name_d'] -= 1
if i == 'e':
e['name_e'] += 1
if i == 'E':
e['name_e'] -= 1
print(a,b,c,d,e)
print('Winner is: ', )
答案
你可能想要使用单个字典,而不是每个字典,如:
scores = {
'a': 0,
'b': 0,
'c': 0,
'd': 0,
'e': 0,
}
然后,您可以在计算得分时跟踪得分最高的玩家:
point_scored = input('Enter series of charachters indicating who scored a point: ')
for i in point_scored:
if not scores.get(i) is None:
scores[i] += 1
elif not scores.get(i.lower()) is None:
scores[i.lower()] -= 1
else:
print(str(i) + ' is not a valid player...')
winner = max(scores, key=scores.get)
print(scores)
print('Winner is ' + winner)
另一答案
这将有效:
max((i, name) for d in (a,b,c,d,e) for name, i in d.items())[1]
另一答案
max_key = ""
max_val = 0
for key, value in d.items():
if (value > max_val):
max_val = value
max_key = key
你是这个意思吗?
另一答案
我找到了答案
winner = (sorted(d.items(), key = lambda x: int(x[1]), reverse = True))
以上是关于如何从最高到最低对字典值进行排序?的主要内容,如果未能解决你的问题,请参考以下文章