Python built-in function—max()

1. Function

The max() method returns the maximum value of the given parameter, which can be a sequence.

Two, source code

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

3. Usage

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

4. Interpretation of parameters

  • The default numeric parameter, the larger value;
  • Character type parameter, the alphabetical order is the latter.
  • key—can be used as a function to specify the method of taking the maximum value.
  • default—used to specify the default value returned when the maximum value does not exist.
  • arg1—character parameter/numeric parameter, default numeric

Five, primary usage

  • Pass in multiple parameters to take the maximum value (tuple, list, set)
max(1,2,3,4,5,6)
  • When an iterable object is passed in, take the maximum value of its elements
a = [1, 8, 6, 4, 5, 6]
tmp = max(a)

If the iterable is empty, the max() function should take a default parameter

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

6. Advanced usage (add parameter key)

When the key parameter is not empty, the function object of the key is used as the judgment standard.
If we want to find the number with the largest absolute value in a set of numbers, we can cooperate with lamda to process it first, and then find the maximum value

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

Guess you like

Origin blog.csdn.net/LiuXF93/article/details/121453893