Skip to content Skip to sidebar Skip to footer

Python: I Have A Tuple, I Found It's Maximum, What Is Its Index?

The example of my problem, so I don't have to put the entire code in here is the following. def mandatos(nr_votes): nr_candidates = len(nr_votes) candidate_with_most_votes

Solution 1:

[CORRECTED:]

A Pythonic way would be

candidate_with_most_votes = max(enumerate(nr_votes), key=lambda x: x[1])[0]

Or, if you want the vote count also,

vote_count, candidate_with_most_votes = max(enumerate(nr_votes), key=lambda x: x[1])

max (like many other functions) allows you to specify a "key" function that's used to extract the value to compare from each element in the tuple. Enumerate yields a tuple of (idx, item) for every item in an iterable. Combining these two, you get what you want.

EXAMPLE:

>>> a=[10,30,20]
>>> max(enumerate(a), key=lambda x: x[1])[0]
1
>>> for i, item in enumerate(a): print(i,item)
(0, 10)
(1, 30)
(2, 20)

Solution 2:

If I understood correctly, you want the position of the max. Try:

candidate_index = nr_votes.index(candidate_with_most_votes)

Post a Comment for "Python: I Have A Tuple, I Found It's Maximum, What Is Its Index?"