创新互联Python教程:Python min()

内置函数min()有助于返回给定 iterable 中的最小元素。也可以在两个或多个参数之间找到最小的元素。

创新互联-专业网站定制、快速模板网站建设、高性价比旬阳网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式旬阳网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖旬阳地区。费用合理售后完善,十余年实体公司更值得信赖。

 # 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)** 

最小()参数:

带有 iterable 的min()函数具有以下参数。

*分钟(可重复,可重复,键,默认)**

参数描述必需/可选
可迭代的诸如列表、元组、集合、字典等可条目。需要
*可重复任意数量的可滴定物;可以不止一个可选择的
传递数据项并进行比较的一种关键功能可选择的
系统默认值如果给定的 iterable 为空,则为默认值可选择的

不带iterable()iterable()函数有以下参数。

【t0 min(arg1、arg2、*args、键)】的缩写

参数描述必需/可选
arg1一个对象;可以是数字、字符串等需要
arg2一个对象;可以是数字、字符串等需要
*参数任意数量的对象可选择的
传递每个参数并进行比较的一个关键函数可选择的

最小()返回值

在传递空迭代器的情况下,它会引发 ValueError 异常。为了避免这种情况,我们可以传递默认参数。 如果我们传递多个迭代器,那么从给定的迭代器中返回最小的项。

| 投入 | 返回值 | | 整数 | 最小整数 | | 线 | 具有最小 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:查找对象的最小值()

 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]

文章名称:创新互联Python教程:Python min()
转载注明:http://www.hantingmc.com/qtweb/news25/91225.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联