Python内置函数—max()

一、作用

max() 方法返回给定参数的最大值,参数可以为序列。

二、源码

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

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

三、用法

    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

四、参数解读

  • 默认数值型参数,取值大者;
  • 字符型参数,取字母表排序靠后者。
  • key—可做为一个函数,用来指定取最大值的方法。
  • default—用来指定最大值不存在时返回的默认值。
  • arg1—字符型参数/数值型参数,默认数值型

五、初级用法

  • 传入多个参数取最大值(元组、列表、集合)
max(1,2,3,4,5,6)
  • 传入可迭代对象时,取其元素最大值
a = [1, 8, 6, 4, 5, 6]
tmp = max(a)

如果可迭代对象为空,max()函数应该采用default参数

print(max((),default=1))   # 传入可迭代对象为空时,必须指定参数default,用来返回默认值 
print(max(()))   #报错

六、高级用法(加入参数key)

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

  • 示例1
a = [-9, -8, 1, 3, -4, 6]
tmp = max(a, key=lambda x: abs(x))
print(tmp)
  • 示例2
prices = {
    
    
			'AEB': 20, 
			'ACC': 15, 
			'LAK': 30, 
			'LDW': 18, 
			'NOP': 50
			}
max(prices, key=lambda k: prices[k])

猜你喜欢

转载自blog.csdn.net/LiuXF93/article/details/121453893