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和Min函数属于functools的工具函数,使用前记得import
from functools import max,min
示例1:求数字序列中的最大值
s=[143,2,456,223,51,24]
res=max(s)
结果:456
示例2:与lambda函数组合——对处理过的序列求最大值
s=[-121,231,-245,56,-22,424]
res=max(s,key=lambda x:abs(x))
结果424
示例3:求字典中值最大的键
dicc={'A':65,'B':66,'C':67,'D':68}
res=max(dicc,key=dicc.get)
结果‘D’
示例4:求字典中序列中,指定键的值最大的字典对象
d1 = {'name': 'egon', 'price': 100}
d2 = {'name': 'rdw', 'price': 666}
d3 = {'name': 'zat', 'price': 1}
ls = [d1, d2, d3]
res=max(ls,key=lambda x:x['price'])
结果:{‘name’: ‘rdw’, ‘price’: 666}