在Python中使用 min() 和 max()
先决条件: Python中的 min() max()
让我们看看关于 min() 和 max()函数的一些有趣事实。这些函数用于计算在其参数中传递的值的最大值和最小值。或者当我们将字符串或字符串列表作为参数传递时,它分别给出字典上的最大值和字典上的最小值。
python3
l= ["ab", "abc", "abd", "b"]
l1="abc"
# prints 'b'
print(max(l))
# prints 'ab'
print(min(l))
#prints 'c'
print(max(l1))
#prints 'a'
print(min(l1))
Python3
# Python code explaining min() and max()
l = ["ab", "abc", "bc", "c"]
print(max(l, key = len))
print(min(l, key = len))
Python3
# Python code explaining min() and max()
def fun(element):
return(len(element))
l =["ab", "abc", "bc", "c"]
print(max(l, key = fun))
# you can also write in this form
print(max(l, key = lambda element:len(element)))
Python3
# Python code explaining min() and max()
l = [{'name':'ramu', 'score':90, 'age':24},
{'name':'golu', 'score':70, 'age':19}]
# here anonymous function takes item as an argument.
print(max(l, key = lambda item:item.get('age')))
在这里,您注意到输出是按照字典顺序排列的。但我们也可以通过简单地传递函数名或 lambda 表达式,根据字符串的长度或根据我们的要求找到输出。
参数:
默认情况下, min() 和 max() 不需要任何额外的参数。但是,它有一个可选参数:
key – function that serves as a key for the min/max comparison
Syntax: max(x1, x2, …, xn, key=function_name)
here x1, x2, x3.., xn passed arguments
function_name : denotes which type of operation you want to perform on these arguments. Let function_name=len, so now output gives according to length of x1, x2.., xn.
返回值:
It returns a maximum or minimum of list according to the passed parameter.
Python3
# Python code explaining min() and max()
l = ["ab", "abc", "bc", "c"]
print(max(l, key = len))
print(min(l, key = len))
abc
c
解释:
在上面的程序中,max()函数有两个参数: l(list) 和 key = len(function_name)。这个 key = len(function_name)函数在比较之前对每个元素进行转换,它取值并返回 1 个值,然后在 max() 或 min() 中使用而不是原始值。这里 key 将列表的每个元素转换为其长度,然后根据其长度比较每个元素。
initially l = [“ab”, “abc”, “bc”, “c”]
when we passed key=len as arguments then it works like
l=[2,3,2,1]
Python3
# Python code explaining min() and max()
def fun(element):
return(len(element))
l =["ab", "abc", "bc", "c"]
print(max(l, key = fun))
# you can also write in this form
print(max(l, key = lambda element:len(element)))
abc
abc
另一个例子:
Python3
# Python code explaining min() and max()
l = [{'name':'ramu', 'score':90, 'age':24},
{'name':'golu', 'score':70, 'age':19}]
# here anonymous function takes item as an argument.
print(max(l, key = lambda item:item.get('age')))
{'age': 24, 'score': 90, 'name': 'ramu'}
类似地,我们可以根据需要使用 min()函数而不是 max()函数。