📅  最后修改于: 2023-12-03 15:32:54.699000             🧑  作者: Mango
The minmax
function in Python is used to find the minimum and maximum values from an iterable object. The function takes one argument, which is the iterable object, and returns a tuple containing the minimum and maximum values from the iterable.
minmax(iterable, default=None, key=lambda x: x)
iterable
: An iterable object, such as a list or tuple, from which to find the minimum and maximum values.default
: The default value to return if the iterable is empty. If not provided, the function will raise a ValueError
.key
: A function to customize the comparison of the elements in the iterable. By default, the comparison is done using the default less-than operator.numbers = [4, 6, 2, 8, 3, 1, 5, 7]
min_num, max_num = minmax(numbers)
print("Minimum number:", min_num)
print("Maximum number:", max_num)
Output:
Minimum number: 1
Maximum number: 8
words = ["apple", "banana", "cherry", "date"]
min_word, max_word = minmax(words)
print("Minimum word:", min_word)
print("Maximum word:", max_word)
Output:
Minimum word: apple
Maximum word: date
person = {"name": "John", "age": 42, "height": 6.2}
min_key, max_key = minmax(person, key=lambda x: person[x])
print("Minimum key:", min_key)
print("Maximum key:", max_key)
Output:
Minimum key: age
Maximum key: height
The minmax
function is a useful tool for finding the minimum and maximum values from an iterable object in Python. It provides an easy and efficient way to perform this common operation, with the ability to customize the comparison of elements using a key function.