How can i get 2 or more indices of a certain value from a list? e.g.
list = [5, 1, 5]
list_max = max(list)
list_max_indices = list.index(list_max)
In this way list_max_indices returns me only one value, the first it encounters, even if there are two values “5”. If I would return also the second index, how I could do?
P.S.
I need this because I want to use the indices to assign the score to the winning players in a card program, to understanding better:
score = [0, 0, 0]
players = [user, first_opponent, second_opponent]
#hypothetic 2+ winning players
score[list_max_indices] += 1
#final score = [1, 0, 1]
or something like
for winning_player in list_max_indices:
score[winning_player] += 1
winning_player += 1
1
To get all of the indices in a list, there are a few different methods you can use.
You could use a list comprehension:
r = [index for index, obj in enumerate(l) if obj == o]
Where l
is the list, and o
is the object you’re looking for the index of. This is equivalent to:
r = []
for index, obj in enumerate(l):
if obj == o:
r.append(obj)
If memory is a constraint, you could also use a generator comprehension:
r = (index for index, obj in enumerate(l) if obj == o)
If happen to need a function for this:
def get_list_indices(l, o):
return [index for index, obj in enumerate(l) if obj == o]
0