python:max
python
本文字数:191 字 | 阅读时长 ≈ 1 min

python:max

python
本文字数:191 字 | 阅读时长 ≈ 1 min

1. max

max(iterable, *[key, default])

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

返回迭代对象中的最大值,其中 key 参数的作用是对迭代对象中的每个元素先用 key 指定的函数进行处理,然后取最大值

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

其中 key 指定的函数可以是库里的,也可以是自定义的

1.1 python 内置函数

list_ = [1, 3, 6, 4, -5, -10]
max(list_, key=abs)
'''
-10
'''

1.2 自定义函数

def func(x):
    return abs(x)
list_ = [1, 3, 6, 4, -5, -10]
max(list_, key=func)
'''
-10
'''

1.3 匿名函数

list_ = [1, 3, 6, 4, -5, -10]
max(list_, key=lambda x:abs(x))
'''
-10
'''

1.4 一些方法

# 找出出现次数最多的数
list_ = [1, 3, 6, 6, -5, -10]
max(list_, key=list_.count)
'''
6
'''
4月 06, 2025
3月 10, 2025
12月 31, 2024