index of max value in a list PYTHON
the max function, it returns the maximum value in the
list rather than the index associated with that value.
How do I return the index?
l.index(max(l)
l.index(max(l)) will give you the index of the first occurrance of the
maximum.
m = max(l)
[ i for i,v in enumerate(l) if v==m ]
will give you a list of all indices where the max occurs. (Putting the
'max(l)' outside the list comprehension prevents it from being evaluated
for each loop element.)
3 comments:
You can use numpy to do it:
# transform to an array
import numpy
l = numpy.array(l)
idx = l.maxarg()
You can also do it in one line with:
idx = x.index(math.max(x))
You can also do it in one line with:
idx = l.index(math.max(l))
Post a Comment