How to randomly return the index of one of the max items in a list in Python?

My program counts the number of times 3 different values โ€‹โ€‹appear and saves them in a list like this classes = [class1,class2,class3]

I want to return the index of the largest value, but these values โ€‹โ€‹will often duplicate. If so, I want to return a randomly selected index between the largest values.

For example, if I have classes = [5,2,5], I want to print either 0 or 2. If I have classes = [1,1,1], then 0,1 and 2 are exact. Finally, if I have classes = [1,10,1], I want to output 1.

So far I have compiled this from other questions, but it does not behave the way I want, and I do not understand why.

classes = [class1,class2,class3]
dupes = [n for n, x in enumerate(classes) if x in classes[:n]]
class_prediction = dupes[random.randint(0,len(dupes))] + 1

(+1 at the end is to return the actual class label instead of the index.)

+4
2

random.choice ,

indices = [idx for idx, val in enumerate(values) if val == largest]
random.choice(indices)

,

>>> import random
>>> values = [5, 2, 5, 3, 1]
>>> largest = max(values)
>>> indices = [idx for idx, val in enumerate(values) if val == largest]
>>> random.choice(indices)
2
>>> random.choice(indices)
0
>>> random.choice(indices)
2
+6

, , , " " , :

import random

def get_random_max(classes):
    maximum_indexes = []
    maximum_value = None

    for i, n in enumerate(classes):
        if maximum_value is None or n > maximum_value:
            maximum_value = n
            maximum_indexes = [i + 1]
        elif n == maximum_value:
            maximum_indexes.append(i + 1)

    return random.choice(maximum_indexes)

print(get_random_max([5, 2, 5]))  # prints 1 or 3 with equal probability
+4

Source: https://habr.com/ru/post/1687465/