python - 报告最高值的键或平局

3 投票
3 回答
1385 浏览
提问于 2025-04-18 10:09

我知道这个问题很简单,可能已经有人回答过了,但我一直找不到答案,可能是因为我用错了搜索词。

我有一个像这样的东西(但要复杂得多):

score = {}
z = 4
while z > 0:
    score[z] = random.randrange(1,12)
    z -= 1

最后我得到了这些值:

score[1] = 7
score[2] = 9
score[3] = 12
score[4] = 7

我想要一个方法把一个变量设置为3,因为score[3]是最大的。

score[1] = 9
score[2] = 9
score[3] = 7
score[4] = 8

在这种情况下,它应该把变量设置为0或者其他什么,因为最高的数字是平局。

3 个回答

2

如果你一定要用字典来表示score,那么你可以使用一种函数的写法:

def index_of_highest_score(scores):
    max_score = max(scores.values())
    keys = []
    for key, value in scores.iteritems():
        if value == max_score:
            keys.append(key)
    if len(keys) > 1:
        return 0
    else:
        return keys[0]

score = {}
score[1] = 7
score[2] = 9
score[3] = 12
score[4] = 7
print index_of_highest_score(score) # Prints 3

score[1] = 9
score[2] = 9
score[3] = 7
score[4] = 8
print index_of_highest_score(score) # Prints 0
5
max_score = max(score.values())
keys = [k for k in score if score[k] == max_score]

这段代码会生成一个列表,里面包含得分最高的键,不管是一个还是多个。

3

使用 collections.Counter

from collections import Counter

score=Counter()
score[1] = 7
score[2] = 9
score[3] = 12
score[4] = 7
print score
Counter({3: 12, 2: 9, 1: 7, 4: 7})
print score.most_common()[0][1],score.most_common()[1][1]
12 9

如果 score.most_common()[0][1] == score.most_common()[1][1],说明有两个相同的最大值,这时候就把变量设置为0。

否则,就把变量设置为 score.most_common()[0][0],这个值是最高分对应的键。

score=Counter()
score[1] = 9
score[2] = 9
score[3] = 7
score[4] = 8
print score
print score.most_common()[0][1],score.most_common()[1][1]
print score.most_common()[0][1]==score.most_common()[1][1]
Counter({1: 9, 2: 9, 4: 8, 3: 7})
9 9
True

撰写回答