min/max内建函数

本文以max()为例,对min/max内建函数进行说明源码

  1. def max(*args, key=None): # known special case of max
  2.     """
  3.     max(iterable, *[, default=obj, key=func]) -> value
  4.     max(arg1, arg2, *args, *[, key=func]) -> value
  5.     With a single iterable argument, return its biggest item. The
  6.     default keyword-only argument specifies an object to return if
  7.     the provided iterable is empty.
  8.     With two or more arguments, return the largest argument.
  9.     """
  10.     pass

初级技巧

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

中级技巧:key属性的使用

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

  1. a = [-9, -8, 1, 3, -4, 6]
  2. tmp = max(a, key=lambda x: abs(x))
  3. print(tmp)

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

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

  1. prices = {
  2.     'A':123,
  3.     'B':450.1,
  4.     'C':12,
  5.     'E':444,
  6. }
  7. # 在对字典进行数据操作的时候,默认只会处理key,而不是value
  8. # 先使用zip把字典的keys和values翻转过来,再用max取出值最大的那组数据
  9. max_prices = max(zip(prices.values(), prices.keys()))
  10. print(max_prices) # (450.1, 'B')

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

  1. prices = {
  2.     'A': 123,
  3.     'B': 123,
  4. }
  5.  
  6. max_prices = max(zip(prices.values(), prices.keys()))
  7. print(max_prices) # (123, 'B')
  8.  
  9. min_prices = min(zip(prices.values(), prices.keys()))
  10. print(min_prices) # (123, 'A')

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值