Get the index of the maximum value (minimum value) of the list
I measured the 5 methods described in Mr. Uzen's article above. For the measurement code, I used Measure and display the processing time.
I also added the processing with numpy that was pointed out in the comment. Except for the conversion cost of array → numpy, numpy was overwhelmingly fast. It was too early, so I increased the number of elements in the target array by an order of magnitude.
Output result (part)
elapsed_time:0.027699708938598633[sec]
elapsed_time:0.15381669998168945[sec]
elapsed_time:0.1455528736114502[sec]
elapsed_time:0.09561371803283691[sec]
elapsed_time:0.07018375396728516[sec]
elapsed_time:0.08819770812988281[sec]
elapsed_time:0.0008273124694824219[sec]
[244347, 674860, 655894, 255695, 678218, 531167, 17071, 288341, 429050, 146444, 291065, 27607, 556887, 298302, 515557, 271078, 883608, 9098, 752318, 276251, 349950, 133988, 955108, 322233, 613472, 844009, 298534, 485112, 106167, 516815, 865031, 286926, 413458, 883781, 910152, 942716, 913758, 853043, 377110, 527816, 478540, 920741, 770539, 169002, 820915, 231827, 423725, 673925, 182482, 14842, 515316, 999412, 152994, 986206, 851899, 403318, 137434, 163888, 46630, 347440, 920191, 506127, 935566, 981816, 353811, 196066, 106365, 739729, 62010, 426593,
Implementation code
import time
import random
import numpy as np
list_name = []
max_value = 1000000
for i in range(max_value ):
list_name.append(random.randint(1,max_value))
start = time.time()
list_name.index(max(list_name))
elapsed_time = time.time() - start
print("elapsed_time:{0}".format(elapsed_time) + "[sec]")
start = time.time()
max(enumerate(list_name), key=lambda x: x[1])[0]
elapsed_time = time.time() - start
print("elapsed_time:{0}".format(elapsed_time) + "[sec]")
start = time.time()
max(range(len(list_name)), key=lambda i: list_name[i])
elapsed_time = time.time() - start
print("elapsed_time:{0}".format(elapsed_time) + "[sec]")
import operator
start = time.time()
max(enumerate(list_name), key=operator.itemgetter(1))[0]
elapsed_time = time.time() - start
print("elapsed_time:{0}".format(elapsed_time) + "[sec]")
start = time.time()
max(zip(list_name, range(len(list_name))))[1]
elapsed_time = time.time() - start
print("elapsed_time:{0}".format(elapsed_time) + "[sec]")
# numpy (array → numpy conversion processing included)
start = time.time()
np_list_name = np.array(list_name)
np_list_name.argmax()
elapsed_time = time.time() - start
print("elapsed_time:{0}".format(elapsed_time) + "[sec]")
# numpy (array → numpy without conversion processing)
np_list_name2 = np.array(list_name)
start = time.time()
np_list_name2.argmax()
elapsed_time = time.time() - start
print("elapsed_time:{0}".format(elapsed_time) + "[sec]")
print(list_name)
I tried to tell in the comments on the blog, but I couldn't find the comment section. Deliver this feeling.
~~ And even the fastest code can't solve a certain problem ... If you know a better way, please let me know. ~~ → Solved!