Python 求一个列表的最小值

def findMin(alist):
    start = time.time()
    findMin = alist[0];
    for i in range(1,len(alist)):
        if alist[i] < findMin:
            findMin = alist[i]
    end = time.time()
    return findMin,end-start

结果如下:

for i in range(5):
    print("the minimum is %d, the process required %10.7f seconds"%(findMin(list(random.randint(1,100) for i in range(1000000)))))
    
the minimum is 1, the process required  0.1043806 seconds
the minimum is 1, the process required  0.0833511 seconds
the minimum is 1, the process required  0.1031568 seconds
the minimum is 1, the process required  0.1031709 seconds
the minimum is 1, the process required  0.0906184 seconds

函数改进一下:

def findMin(alist):
    start = time.time()
    findMin = alist[0];
    for i in alist:
        if i < findMin:
            findMin = i
    end = time.time()
    return findMin,end-start

因为python 中for循环可以对元素进行遍历,所以可以这样写。
结果如下:

for i in range(5):
    print("the minimum is %d, the process required %10.7f seconds"%(findMin_1(list(random.randint(1,100) for i in range(1000000)))))
    
the minimum is 1, the process required  0.0530787 seconds
the minimum is 1, the process required  0.0150602 seconds
the minimum is 1, the process required  0.0606675 seconds
the minimum is 1, the process required  0.0580323 seconds
the minimum is 1, the process required  0.0625741 seconds

运行时间比上一种方法要短。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 〇、前言 本文共108张图,流量党请慎重! 历时1个半月,我把自己学习Python基础知识的框架详细梳理了一遍。 ...
    Raxxie阅读 19,598评论 17 410
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,373评论 4 16
  • 1、 周六,用招商银行的积分兑换了一杯星巴克的美式,还加了三块钱升了大杯,然后把刚在路上捡到的一元硬币掉在了地上,...
    大可木木林阅读 237评论 0 0
  • 无火香薰英文名字:Read Diffuser,行内称:“藤条挥发液”“无火香薰”,是欧美近年来十分流行的室内加香用...
    金奶奶阅读 8,726评论 0 1
  • “亲爱的,麻烦你明天给应童老师寄一块药皂过去,别提我哈!她牙痛,告诉她药皂是万能皂!”身在德国的老友半夜三更给我发...
    雪纷阅读 525评论 3 12

友情链接更多精彩内容