欢迎访问宙启技术站
智能推送

Python中的min()和max()函数:使用方法和示例

发布时间:2023-05-31 01:10:48

Python的内置函数min()和max()都是用来找到一个可迭代对象中的最小值和最大值。这些函数对于快速查找列表或其他数据集合中的最小值和最大值非常有用。

下面是min()和max()的使用方法和示例。

使用方法:

使用方式非常简单,仅需要传递一个可迭代对象即可。min()函数返回可迭代对象中的最小元素,而max()函数返回可迭代对象中的最大元素。

示例:

下面是一些示例,展示了min()和max()函数在不同的场景下的使用方法。

1. 找到列表中的最大值和最小值

numbers = [2, 7, 4, 1, 8, 9, 6, 3, 5]

min_number = min(numbers)
max_number = max(numbers)

print("Minimum number is:", min_number)
print("Maximum number is:", max_number)

输出:

Minimum number is: 1
Maximum number is: 9

2. 找到字典中根据值排序后的最小值和最大值

students = { 'John': 78, 'Bob': 89, 'Alice': 92, 'Mike': 69 }

min_student = min(students, key=students.get)
max_student = max(students, key=students.get)

print("The student with the lowest score is:", min_student)
print("The student with the highest score is:", max_student)

输出:

The student with the lowest score is: Mike
The student with the highest score is: Alice

3. 找到列表中的最长和最短的字符串

fruits = ['banana', 'apple', 'orange', 'kiwi', 'pear']

shortest_fruit = min(fruits, key=len)
longest_fruit = max(fruits, key=len)

print("The shortest fruit is:", shortest_fruit)
print("The longest fruit is:", longest_fruit)

输出:

The shortest fruit is: kiwi
The longest fruit is: banana

4. 找到元组中 个元素的最大和最小值

stock_prices = [('GOOG', 100), ('APPL', 200), ('NFLX', 300), ('TSLA', 400)]

min_price = min(stock_prices, key=lambda x: x[0])
max_price = max(stock_prices, key=lambda x: x[0])

print("The stock with the lowest first letter is:", min_price[0])
print("The stock with the highest first letter is:", max_price[0])

输出:

The stock with the lowest first letter is: APPL
The stock with the highest first letter is: TSLA

总之,min()和max()函数是Python中很有用的函数,可用于查找可迭代对象中的最小和最大值。使用这些函数,你可以更快地查找列表或其他数据集合中的最小和最大值。