美文网首页
Python 求一个列表的最小值

Python 求一个列表的最小值

作者: Golden_humble | 来源:发表于2018-06-17 22:44 被阅读0次
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

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

相关文章

  • Python 求一个列表的最小值

    结果如下: 函数改进一下: 因为python 中for循环可以对元素进行遍历,所以可以这样写。结果如下: 运行时间...

  • 105、python isinstance 函数

    例如查找列表中的最大最小值: 代码中isinstance函数用法: isinstance是Python中的一个内建...

  • [基础] 在Python中获得字典列表中最大值与最小值

    假设有字典列表: 要求price的最大值与最小值 最原始的方法: 刚学Python时会这么写... 先使用列表推导...

  • 第十五章:内置函数

    python有一些常用的内置函数: 数学函数 abs() 获取绝对值 min()求最小值 max()求最大值 ha...

  • 2019-05-14

    日志文本筛选-sort awk 求最大值: 求最小值: 求和: 求平均值: 求最大值 求最大值 求最小值 中位数

  • 线性表最值问题

    找最小值 找最大值 顺序表求最大值 顺序表求最小值 带头结点单链表求最大值 带头结点单链表求最小值 q是 最大值/...

  • JS求一个数的十倍的最小值

    求一个数的十倍的最小值 求一个数的第一位数字加1的最小值

  • python:numpy数组常用的统计函数

    数据准备: 求和 求均值 求中值 求最大值和最小值 求极值(最大值和最小值之差)、 6、标准差

  • day06 作业

    已知一个列表,求列表中心元素。 已知一个列表,求所有元素和。 已知一个列表,输出所有奇数下标元素。 已知一个列表,...

  • 一阶段day7-03作业

    1、已知一个列表,求列表中心元素; 2、已知一个列表,求列表所有元素和; 3、已知一个列表,输出所有奇数下标元素;...

网友评论

      本文标题:Python 求一个列表的最小值

      本文链接:https://www.haomeiwen.com/subject/qbrgeftx.html