[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Index of maximum element in list

Terry Reedy

1/26/2008 7:33:00 AM


"Henry Baxter" <henry.baxter@gmail.com> wrote in message
news:8d04436f0801251519g482a697dn625223b6d46e8f2c@mail.gmail.com...
| Thanks Hexamorph and Neal. Somehow I didn't make the connection with
using
| 'index', but I'm all sorted out now :)
|
| On Jan 25, 2008 1:47 PM, Hexamorph <hexamorph@gmx.net> wrote:
|
| > Henry Baxter wrote:
| > > Oops, gmail has keyboard shortcuts apparently, to continue:
| > >
| > > def maxi(l):
| > > m = max(l)
| > > for i, v in enumerate(l):
| > > if m == v:
| > > return i
| > >
| >
| > What's about l.index(max(l)) ?

Both of these methods scan the list twice. The two given by RH and SDD do
so just once. Both of those will give the index of the of the last maximum
value. If you want the index of the first max value (you did not specify
;-), write an explicit loop.



2 Answers

Paul Rubin

1/26/2008 7:36:00 AM

0

"Terry Reedy" <tjreedy@udel.edu> writes:
> | > What's about l.index(max(l)) ?
>
> Both of these methods scan the list twice. The two given by RH and SDD do
> so just once. Both of those will give the index of the of the last maximum
> value. If you want the index of the first max value (you did not specify
> ;-), write an explicit loop.

max((v,-i) for i,v in enumerate(l))

Paul Rubin

1/26/2008 7:40:00 AM

0

"Terry Reedy" <tjreedy@udel.edu> writes:
> | > What's about l.index(max(l)) ?
>
> Both of these methods scan the list twice. The two given by RH and SDD do
> so just once. Both of those will give the index of the of the last maximum
> value. If you want the index of the first max value (you did not specify
> ;-), write an explicit loop.

How about (corrected but still untested):

-max((v,-i) for i,v in enumerate(l))[1]

I may have still missed something.