As a python programmer, do you really know how to use the max() and min() functions?

Tianyuan prodigal son 2020-11-13 09:06:23
python programmer really know use


stay Python Of the more than 70 built-in functions of ,max() and min() They are two commonly used ones , Used to find the maximum and minimum values in a set of data . These two functions seem simple , In fact, there are many unexpected functions hidden , In especial key Parameters , Add similar to these two functions map() Function functions . If applied in code , There must be some magic work 、 Fantastic feeling , breathtaking !

1. Typical application scenarios

This is a max() and min() The most common application scenario of function : Returns the maximum from multiple numeric arguments / minimum value , Or return the largest in a numeric list / minimum value . The numerical type here , It refers to integers and floating points .

>>> max(1,3,5,7) # Returns the maximum value of multiple numeric parameters 
7
>>> min([2,4,6,8]) # Returns the minimum value in a numeric list 
2

2. Compare strings

Type of input parameter or list element , Except for numerical , It can also be a string , But you can't mix numeric and string . The rule for comparing the size of two strings starts with the first character ASCII Code value , If equal , Then compare the last character , Until the size comes out .

>>> max(['a','b','c']) # Returns the largest string in the list 
'c'
>>> min('2020-06-23 12:00:00', '2020-06-23 11:50:00') # Returns the earliest date time string 
'2020-06-23 11:50:00'
>>> max('1', '9', '10', '100') # Returns the largest string among multiple strings 
'9'
>>> min('1', '9', '10', '100') # Returns the smallest string among multiple strings 
'1'

3. Compare lists or tuples

Except for numerical 、 String type ,max() and min() Function can also be used to compare the size of a list or tuple : Compare the elements in order , Until the size comes out . Of course , The elements used for comparison must be of the same type , It's either numerical , Either it's all string type .

>>> max([8,4],[6,8]) # Returns the largest list of multiple lists 
[8, 4]
>>> max([8,4],[8,4,2]) # Returns the largest list of multiple lists 
[8, 4, 2]
>>> min(['8',4],['8',4,'2']) # Returns the smallest list of multiple lists 
['8', 4]
>>> min(('8',4, '3'),('8',4,'2')) # Returns the smallest tuple among multiple tuples 
('8', 4, '2')

4. Find the dictionary 、 character string 、 The maximum and minimum in an iterator

max() and min() Function can not only compare the size of elements in a list or tuple , You can also gather from 、 Dictionaries 、 character string 、range object 、 Find the largest and smallest elements in objects such as iterators .

>>> max({
3,4,5,6}) # Returns the maximum value in the collection 
6
>>> min({
'x':5, 'y':7, 'z':3}) # Returns the minimum value in a dictionary element , The result is the smallest bond 
'x'
>>> max("I'm xufive.") # Returns the maximum character in a string ( It's a bit of an accident ?)
'x'
>>> min("I'm xufive.") # Returns the smallest character in a string 
' '
>>> max(range(5)) # range() The function returns a range object 
4
>>> max(map(abs, [-1,2,-3])) # map() Function returns an iterator 
3

5. Use key Parameters

We noticed that , Use max() and min() Function returns the maximum of the dictionary / minimum value , What you actually get is the largest key in the dictionary / minimum value . So how to get the maximum value of the dictionary / What about the minimum value ? It's simple , Use max() and min() Functional key Parameters . however , One caveat , Use key Parameters , The largest in the dictionary is returned / The minimum key , Not the biggest / minimum value .

>>> d = {
'x':5, 'y':7, 'z':3}
>>>> min(d) # Returns the smallest key in the dictionary 
'x'
>>> min(d, key=lambda x:d[x]) # The key that returns the minimum value in the dictionary , Not the minimum 
'z'
>>> max(d) # Returns the largest key in the dictionary 
'z'
>>> max(d, key=lambda x:d[x]) # The key that returns the maximum value in the dictionary , Not the maximum 
'y'

6. Comprehensive practice

Last , Let's do two exercises , have a look max() and min() How powerful a function is . These two questions are not difficult , Beginners can give answers easily , however , If you want to write elegantly and beautifully , Not max() and min() Functions cannot be .

  1. list [1,3,5,7,9,11,13,15,17] in , Which element has the smallest sine value ?
  2. list [8,5,2,4,3,6,5,5,1,4,5] in , Which element appears most frequently ?

problem 1 The reference answer to :

>>> import math
>>> a = [1,3,5,7,9,11,13,15,17]
>>> min(a, key=math.sin)
11
>>> math.sin(11) # Elements 11 The sine value of is the smallest 
-0.9999902065507035

problem 2 The reference answer to :

>>> a = [8,5,2,4,3,6,5,5,1,4,5]
>>> max(set(a), key=a.count)
5
>>> a.count(5) # Elements 5 There is 4 Time , Most times 
4
版权声明
本文为[Tianyuan prodigal son]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database