本篇以min()函数为例进行说明,max()同理。
先来看看源码
def min(*args, key=None): # known special case of min
"""
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
"""
pass
用法一:
# 常规用法,对可迭代对象求最小值
a = min(1, 2, 3)
print(a)
b = [1, 2, 3]
res = min(b)
print(res)
用法二:
# 当第二参数key不为空时,以key的函数对象为依据进行判断
a = [1, 2, 3, -4]
res1 = min(a)
res2 = min(a, key=lambda x: abs(x))
print(res1)
print(res2)
# 输出结果
-4
1
用法三:
# 对字典进行数据操作时,默认只会对kye,而不是value,
#若是想求得字典中值最大的那组数据需要先用zip函数进行翻转
dict = {1: 'c', 2: 'b', 3: 'a'}
min_dict1 = min(dict)
min_dict = min(zip(dict.values(), dict.keys()))
print(min_dict1)
print(min_dict)
# 输出结果
1
('a', 3)
对于翻转后的字典键值对,当键(原来的值)相等时才会对比值(原来的键)
版权声明:本文为weixin_29370665原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。