内置函数之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 
 6     With a single iterable argument, return its biggest item. The
 7     default keyword-only argument specifies an object to return if
 8     the provided iterable is empty.
 9     With two or more arguments, return the largest argument.
10     """
11     pass

 简单使用:

ret = max(1, 2, 4)
print(ret)

  结果:

4

  

一般使用:

当key不为空时,就以key的函数对象为判断的标准.

如果我们想找出一组数中绝对值最大的书,就可以配合lambda先进行处理,再找出最大值.

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

  结果:

-9

骚操作:找出字典中值最大的那组数据

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

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

  结果:

(450.1, 'B')

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

prices = {
    'A': 123,
    'B': 123
}
max_prices = max(zip(prices.values(), prices.keys()))
print(max_prices)
min_prices = min(zip(prices.values(), prices.keys()))
print(min_prices)

  结果:

(123, 'B')
(123, 'A')

  

dic = {
    'k1': 10,
    'k2': 100,
    'k3': 30
}
print(max(dic))
print(dic[max(dic, key= lambda k: dic[k])])

  结果:

k3
100

  

猜你喜欢

转载自www.cnblogs.com/ZN-225/p/9588143.html