python - 具有最高价值或平局的报告密钥

时间:2014-06-17 22:52:59

标签: python

我知道这很简单,而且可能已经在某个地方得到了解答,但我在任何地方找到它都有很多麻烦,可能是因为我在寻找错误的术语。

我有类似的东西(但更复杂):

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,因为得分[3]是最大的。

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

在这个例子中,它应该将变量设置为0或者其他东西,因为最高的数字是平局。

3 个答案:

答案 0 :(得分:4)

max_score = max(score.values())
keys = [k for k in score if score[k] == max_score]

这会生成一个得分最高的键列表,无论是一个还是多个。

答案 1 :(得分: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

答案 2 :(得分:2)

使用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

else set variable to 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