Home Backend Development Python Tutorial Detailed introduction to Python max built-in functions

Detailed introduction to Python max built-in functions

Dec 05, 2016 pm 01:27 PM
python

Python max内置函数

max(iterable, *[, key, default])

max(arg1, arg2, *args[, key])

Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).

 说明:

  1. 函数功能为取传入的多个参数中的最大值,或者传入的可迭代对象元素中的最大值。默认数值型参数,取值大者;字符型参数,取字母表排序靠后者。还可以传入命名参数key,其为一个函数,用来指定取最大值的方法。default命名参数用来指定最大值不存在时返回的默认值。

  2. 函数至少传入两个参数,但是有只传入一个参数的例外,此时参数必须为可迭代对象,返回的是可迭代对象中的最大元素。

>>> max(1) # 传入1个参数报错
Traceback (most recent call last):
 File "<pyshell#0>", line 1, in <module>
  max(1)
TypeError: 'int' object is not iterable
>>> max(1,2) # 传入2个参数 取2个中较大者
2
>>> max(1,2,3) # 传入3个参数 取3个中较大者
3
>>> max('1234') # 传入1个可迭代对象,取其最大元素值
'4'
Copy after login

  3. 当传入参数为数据类型不一致时,传入的所有参数将进行隐式数据类型转换后再比较,如果不能进行隐式数据类型转换,则会报错。

>>> max(1,1.1,1.3E1) # 整数与浮点数可取最大值
13.0
>>> max(1,2,3,'3') # 数值与字符串不能取最大值
Traceback (most recent call last):
 File "<pyshell#5>", line 1, in <module>
  max(1,2,3,'3')
TypeError: unorderable types: str() > int()

>>> max([1,2],[1,3]) # 列表与列表可取最大值
[1, 3]
>>> max([1,2],(1,3)) # 列表与元组不能取最大值
Traceback (most recent call last):
 File "<pyshell#7>", line 1, in <module>
  max([1,2],(1,3))
TypeError: unorderable types: tuple() > list()

Copy after login

  4. 当存在多个相同的最大值时,返回的是最先出现的那个最大值。

#定义a、b、c 3个列表
>>> a = [1,2]
>>> b = [1,1]
>>> c = [1,2]

#查看a、b、c 的id
>>> id(a)
68128320
>>> id(b)
68128680
>>> id(c)
68128240

#取最大值
>>> d = max(a,b,c)
>>> id(d)
68128320

#验证是否最大值是否是a
>>> id(a) == id(d)
True

Copy after login

  5. 默认数值型参数,取值大者;字符型参数,取字母表排序靠后者;序列型参数,则依次按索引位置的值进行比较取最大者。还可以通过传入命名参数key,指定取最大值方法。

>>> max(1,2) # 取数值大者
2
>>> max('a','b') # 取排序靠后者
'b'
>>> max('ab','ac','ad') # 依次按索引比较取较大者
'ad'

>>> max(-1,0) # 数值默认去数值较大者
0
>>> max(-1,0,key = abs) # 传入了求绝对值函数,则参数都会进行求绝对值后再取较大者
-1

Copy after login

  6. key参数的另外一个作用是,不同类型对象本来不能比较取最大值的,传入适当的key函数,变得可以比较能取最大值了。

>>> max(1,2,'3') #数值和字符串不能取最大值
Traceback (most recent call last):
 File "<pyshell#21>", line 1, in <module>
  max(1,2,'3')
TypeError: unorderable types: str() > int() 
>>> max(1,2,'3',key = int) # 指定key为转换函数后,可以取最大值
'3'

>>> max((1,2),[1,1]) #元组和列表不能取最大值
Traceback (most recent call last):
 File "<pyshell#24>", line 1, in <module>
  max((1,2),[1,1])
TypeError: unorderable types: list() > tuple()
>>> max((1,2),[1,1],key = lambda x : x[1]) #指定key为返回序列索引1位置的元素后,可以取最大值
(1, 2)
复制代码
  
Copy after login

7. 当只传入的一个可迭代对象时,而且可迭代对象为空,则必须指定命名参数default,用来指定最大值不存在时,函数返回的默认值。

>>> max(()) #空可迭代对象不能取最大值
Traceback (most recent call last):
 File "<pyshell#26>", line 1, in <module>
  max(())
ValueError: max() arg is an empty sequence
>>> max((),default=0) #空可迭代对象,指定default参数为默认值
0
>>> max((),0) #默认值必须使用命名参数进行传参,否则将被认为是一个比较的元素
Traceback (most recent call last):
 File "<pyshell#27>", line 1, in <module>
  max((),0)
TypeError: unorderable types: int() > tuple()
Copy after login

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles