如何在python中获取列表的最小和最大元素

如何在python中获取列表的最小和最大元素,第1张

如何在python中获取列表的最小和最大元素

我能想到的最快的方法是对原始列表进行排序,然后选择第一个和最后一个元素。这样可以避免多次循环,但是会破坏列表的原始结构。这可以通过简单地复制列表并仅对复制的列表进行排序来解决。我很好奇这是否比使用此快速示例脚本仅使用max()和min()更慢:

import timel = [1,2,4,5,3]print "Run 1"t1 = time.time()print "Min =", min(l)print "Max =", max(l)print "time =", time.time() - t1print ""print "l =", lprint ""l = [1,2,4,5,3]l1 = list(l)print "Run 2"t1 = time.time()l1.sort()print "Min =", l1[0]print "Max =", l1[-1]print "time =", time.time() - t1print ""print "l =", lprint "l1 =", l1print ""l = [1,2,4,5,3]print "Run 3"minimum = float('inf')maximum = float('-inf')for item in l:    if item < minimum:        minimum = item    if item > maximum:        maximum = itemprint "Min =", minimumprint "Max =", maximumprint "time =", time.time() - t1print ""print "l =", l

出乎意料的是,第二种方法在我的计算机上速度提高了约10ms。不确定使用非常大的列表会产生多大的效果,但是这种方法至少对于您提供的示例列表而言更快。

我在计时脚本中添加了@Martijn Pieters的简单循环算法。(因为计时是值得在此问题中探讨的唯一重要参数。)我的结果是:

Run 1: 0.0199999809265sRun 2: 0.00999999046326sRun 3: 0.0299999713898s

编辑:包括timeit模块进行计时。

import timeitfrom random import shufflel = range(10000)shuffle(l)def Run_1():    #print "Min =", min(l)    #print "Max =", max(l)    return min(l), max(l)def Run_2():    l1 = list(l)    l1.sort()    #print "Min =", l1[0]    #print "Max =", l1[-1]    return l1[0], l1[-1]def Run_3():    minimum = float('inf')    maximum = float('-inf')    for item in l:        if item < minimum: minimum = item        if item > maximum: maximum = item    #print "Min =", minimum    #print "Max =", maximum    return minimum, maximumif __name__ == '__main__':    num_runs = 10000    print "Run 1"    run1 = timeit.Timer(Run_1)    time_run1 = run1.repeat(3, num_runs)    print ""    print "Run 2"    run2 = timeit.Timer(Run_2)    time_run2 = run2.repeat(3,num_runs)    print ""    print "Run 3"    run3 = timeit.Timer(Run_3)    time_run3 = run3.repeat(3,num_runs)    print ""    print "Run 1"    for each_time in time_run1:        print "time =", each_time    print ""    print "Run 2"    for each_time in time_run2:        print "time =", each_time    print ""    print "Run 3"    for each_time in time_run3:        print "time =", each_time    print ""

我的结果是:

Run 1time = 3.42100585452time = 3.39309908229time = 3.47903182233Run 2time = 26.5261287922time = 26.2023346397time = 26.7324208568Run 3time = 3.29800945144time = 3.25067545773time = 3.29783778232

对于大型数组,sort算法非常慢。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5663457.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存