Screaming Loud

日々是精進

リスト内の最大値を見つける

最大の値を見つけるのは簡単だが,そのindexを取るのはそういえばどうやるんだっけ?
と思い,少し調べて速度比較してみた.

from itertools import count
from operator import itemgetter
from time import clock
import random

def func1(x):
    return x.index(max(x))

def func2(x):
    xs = zip(x,count())
    return max(xs,key=itemgetter(0))[1]

def func3(x):
    xs = zip(x,count())
    return max(xs)[1]

def func4(x):
    return max(xrange(len(x)), key=lambda i: x[i])

if __name__ == "__main__":
    x = range(1000000)
    random.shuffle(x)

    st = clock()
    print func1(x)
    ed = clock()
    print ed - st

    st = clock()
    print func2(x)
    ed = clock()
    print ed - st

    st = clock()
    print func3(x)
    ed = clock()
    print ed - st

    st = clock()
    print func4(x)
    ed = clock()
    print ed - st

結果は次の通り

927845
0.13
927845
0.48
927845
0.36
927845
0.19

Simple is the best!