Tutorial Study Image

Python min()

内置函数 min() 用于返回给定可迭代对象中的最小元素。也可以用于查找两个或多个参数中的最小元素。


# to find the smallest item in an iterable
min(iterable, *iterables, key, default)
 

# to find the smallest item between two or more objects
min(arg1, arg2, *args, key)
  

min() 参数

带有可迭代对象的 min() 函数具有以下参数。

min(iterable, *iterables, key, default)

参数 描述 必需/可选
可迭代对象 一个可迭代对象,例如列表、元组、集合、字典等。 必需
*iterables 任意数量的可迭代对象;可以多于一个 可选
一个键函数,可迭代对象传入后在此函数中进行比较 可选
默认值 如果给定的可迭代对象为空,则为默认值 可选

 

不带可迭代对象的 min() 函数具有以下参数。

min(arg1, arg2, *args, key)

参数 描述 必需/可选
arg1 一个对象;可以是数字、字符串等 必需
arg2 一个对象;可以是数字、字符串等 必需
*args 任意数量的对象 可选
key  一个键函数,每个参数传入后在此函数中进行比较 可选

min() 返回值

如果传入空迭代器,它将引发 ValueError 异常,为避免此情况,我们可以传入 default 参数。
如果传入多个迭代器,则返回给定迭代器中最小的项。

输入 返回值
整型 最小整数
字符串 Unicode 值最小的字符

Python 中 min() 方法的示例

示例 1:获取列表中最小的项


number = [13, 2, 8, 25, 10, 46]
smallest_number = min(number);

print("The smallest number is:", smallest_number)
Output
 

输出

The smallest number is: 2

示例 2:列表中最小的字符串


languages = ["Python", "C Programming", "Java", "JavaScript"]
smallest_string = min(languages);

print("The smallest string is:", smallest_string)
 

输出

The smallest string is: C Programming

示例 3:在字典中查找 min()


square = {2: 4, 3: 9, -1: 1, -2: 4}

# the smallest key
key1 = min(square)
print("The smallest key:", key1)    # -2

# the key whose value is the smallest
key2 = min(square, key = lambda k: square[k])

print("The key with the smallest value:", key2)    # -1

# getting the smallest value
print("The smallest value:", square[key2])    # 1
 

输出

TThe smallest key: -2
The key with the smallest value: -1
The smallest value: 1

示例 4:查找给定数字中的最小值


result = min(4, -5, 23, 5)
print("The minimum number is:", result)
 

输出

The minimum number is -5

示例 5:查找对象的 min()


class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __str__(self):
        return 'Data[%s]' % self.id


def get_data_id(data):
    return data.id


# min() with objects and key argument
list_objects = [Data(1), Data(2), Data(-10)]

print(min(list_objects, key=get_data_id))
 

输出

Data[-10]