> See Subject. a = [1,4,9,3]. Find max, 9, then index to it, 2.
Here are a few ways.
>>> a = [1,4,9,3]
>>> max_index = max(xrange(len(a)), key=a.__getitem__)
>>> max_index
2
>>> # Or:
... max_index = max((n, i) for i, n in enumerate(a))[1]
>>> max_index
2
>>> # Or:
... from itertools import *
>>> max_index = max(izip(a, count()))[1]
>>> max_index
2
--
Arnaud
The most obvious would be a.index(max(a)). Is that what you wanted ?
cheers,
- steve
> "W. eWatson" <wolft...@invalid.com> writes:
>
>> See Subject. a = [1,4,9,3]. Find max, 9, then index to it, 2.
>
> Here are a few ways.
[...]
My copy past went wrond and I forgot the first one:
>>> a = [1,4,9,3]
>>> max_index = a.index(max(a))
>>> max_index
2
--
Arnaud
The disadvantage of that is that it's O(2N) instead of O(N).
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/
"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
<Tongue-in-cheek> Well you could do this:
a.sort ()
return -1
TJG
> In article <4B7A91B1...@lonetwin.net>, steve <st...@lonetwin.net> wrote:
>>On 02/16/2010 05:49 PM, W. eWatson wrote:
>>>
>>> See Subject. a = [1,4,9,3]. Find max, 9, then index to it, 2.
>>
>>The most obvious would be a.index(max(a)). Is that what you wanted ?
>
> The disadvantage of that is that it's O(2N) instead of O(N).
:-)
Joke aside, even though you traverse the list twice, it may still be
quicker than other solutions because both max and list.index are C
functions and no intermediate object is constructed.
--
Arnaud
I don't think you understand order notation. There's no such thing as O(2N).
To answer the original question, how about:
max(enumerate(l), key=lambda x: x[1])[0]
As to whether this is faster than index(max()), you'd have to time it.
-Tom