首页 > 其他 > 详细

内置函数:min 用法

时间:2017-11-12 22:36:47      阅读:303      评论:0      收藏:0      [点我收藏+]

内置函数:min 用法

源码

def min(*args, key=None): # known special case of min
"""
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value

With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
"""
pass

基础用法

tes = min(1,2,4)
print(tes)
#可迭代对象
a = [1, 2, 3, 4, 5, 6]
tes = min(a)
print(tes)

 

key属性的使用

当key参数不为空时,就以key的函数对象为判断的标准。
如果我们想找出一组数中绝对值最小的数,就可以配合lamda先进行处理,再找出最小值

a = [-9, -8, 11, 23, -4, 6]
tes = min(a, key=lambda x: abs(x))
print(tes)

 

高级技巧:找出字典中值最小的那组数据

如果有一组商品,其名称和价格都存在一个字典中,可以用下面的方法快速找到价格最贵的那组商品:

prices = {
    A:123,
    B:450.1,
    C:12,
    E:444,
}
# 在对字典进行数据操作的时候,默认只会处理key,而不是value
# 先使用zip把字典的keys和values翻转过来,再用min取出值最小的那组数据
min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (450.1, ‘B‘)

当字典中的value相同的时候,才会比较key:

prices = {
    A: 123,
    B: 123,
}

min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (123, ‘B‘)

min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices) # (123, ‘A‘)

 

 

和max用法基本一致

 

内置函数:min 用法

原文:http://www.cnblogs.com/bigtreei/p/7823266.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!