本文向您介绍了Python的一个非常有趣且鲜为人知的函数,即 麦克斯() 和 min() 现在,当与它们的C++对应比较时,它们只允许两个参数,它们过于严格地是浮点、int或char,这些函数是 不仅限于2个元素 但是 可以将许多元素作为参数保存,还可以支持字符串 在他们的参数中,因此允许按字典顺序显示最小或最大的字符串。详细功能说明如下。
null
此函数用于计算在其参数中传递的值的最大值,以及如果字符串作为参数传递,则按字典顺序计算的最大值。
Syntax : max(a,b,c,..,key,default)Parameters : a,b,c,.. : similar type of data.key : key function where the iterables are passed and comparison is performeddefault : default value is passed if the given iterable is emptyReturn Value : Returns the maximum of all the arguments.Exceptions : Returns TypeError when conflicting types are compared.
Python3
# Python code to demonstrate the working of # max() # printing the maximum of 4,12,43.3,19,100 print ( "Maximum of 4,12,43.3,19 and 100 is : " ,end = "") print ( max ( 4 , 12 , 43.3 , 19 , 100 ) ) |
输出:
Maximum of 4,12,43.3,19 and 100 is : 100
此函数用于计算在其参数中传递的值的最小值,如果字符串作为参数传递,则用于计算字典中的最小值。
Syntax : min(a,b,c,.., key,default)Parameters : a,b,c,.. : similar type of data.key : key function where the iterables are passed and comparison is performeddefault : default value is passed if the given iterable is emptyReturn Value : Returns the minimum of all the arguments.Exceptions : Returns TypeError when conflicting types are compared.
Python3
# Python code to demonstrate the working of # min() # printing the minimum of 4,12,43.3,19,100 print ( "Minimum of 4,12,43.3,19 and 100 is : " ,end = "") print ( min ( 4 , 12 , 43.3 , 19 , 100 ) ) |
输出:
Minimum of 4,12,43.3,19 and 100 is : 4
例外
1.类型错误: 这些函数在 比较冲突的数据类型 .
Python3
# Python code to demonstrate the Exception of # min() and max() # printing the minimum of 4,12,43.3,19, "GeeksforGeeks" # Throws Exception print ( "Minimum of 4,12,43.3,19 and GeeksforGeeks is : " ,end = "") print ( min ( 4 , 12 , 43.3 , 19 , "GeeksforGeeks" ) ) |
输出:
Minimum of 4,12,43.3,19 and GeeksforGeeks is :
运行时错误:
Traceback (most recent call last): File "/home/b5da1d7f834a267f94fbbefe1b31a83c.py", line 7, in print (min( 4,12,43.3,19,"GeeksforGeeks" ) )TypeError: unorderable types: str() < int()
实际应用
其中一个实际应用是发现 词典学上最大和最小的 指字符串,即在字典中最先出现或最后出现的字符串。
Python3
# Python code to demonstrate the Application of # min() and max() # printing the word occurring 1st among these in dict. # "geeks", "manjeet", "algorithm", "programming" print ( "The word occurring 1st in dict. among given is : " ,end = "") print ( min ( "geeks" , "manjeet" , "algorithm" , "programming" ) ) # printing the word occurring last among these in dict. # "geeks", "manjeet", "algorithm", "programming" print ( "The word occurring last in dict. among given is : " ,end = "") print ( max ( "geeks" , "manjeet" , "algorithm" , "programming" ) ) |
输出:
The word occurring 1st in dict. among given is : algorithmThe word occurring last in dict. among given is : programming
本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END