English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La fonction max() de Python retourne l'élément le plus grand d'un itérable. Elle peut également être utilisée pour trouver l'élément le plus grand entre deux ou plusieurs arguments.
La fonction max() a deux formes :
// Trouver l'élément le plus grand dans l'itération max(iterable, *iterables, key, default) // Trouver l'élément le plus grand entre deux ou plusieurs objets max(arg1, arg2, *args, key)
Pour trouver l'élément le plus grand de l'itérable, nous utilisons la syntaxe suivante :
max(iterable, *iterables, key, default)
iterable -itération, par exemple une liste, un tuple, un ensemble, un dictionnaire, etc.
*iterables(可选) -un nombre quelconque d'éléments itérables ; il peut y en avoir plusieurs
key(可选) -transmet un objet itérable et exécute la comparaison en fonction de son retour de valeur
default(可选) -si l'iterable donné est vide, il prend la valeur par défaut
number = [3, 2, 8, 5, 10, 6] largest_number = max(number); print("Le plus grand nombre est :", largest_number)
Output result
Le plus grand nombre est : 10
si les éléments de l'iterable sont des chaînes de caractères, retourne l'élément le plus grand (trié par ordre alphabétique).
languages = ["Python", "C Programming", "Java", "JavaScript"] largest_string = max(languages); print("The largest string is:", largest_string)
Output result
The largest string is: Python
If it is a dictionary, then max() returns the largest key. Let's use the key parameter so that we can find the dictionary key with the largest value.
square = {2: 4, -3: 9, -1: 1, -2: 4} # the largest key key1 = max(square) print("The largest key:", key1) # 2 # The key with the largest value key2 = max(square, key = lambda k: square[k]) print("The key with the largest value:", key2) # -3 # Get the largest value print("The largest value:", square[key2]) # 9
Output result
The largest key: 2 The key with the largest value: -3 The largest value: 9
In the second max() function, we willLambda functionis passed to the key parameter.
key = lambda k: square[k]
This function returns the value of the dictionary. It returns the key with the maximum value (not the dictionary key).
To find the maximum object among two or more parameters, we can use the following syntax:
max(arg1, arg2, *args, key)
arg1-An object; it can be a number, string, etc.
arg2-An object; it can be a number, string, etc.
* args(Optional)-Any number of objects
key (Optional)-Pass a key function for each parameter and compare based on its return value
By passing the corresponding parameters, the max() function finds the maximum item among two or more objects.
result = max(4, -5, 23, 5) print("The largest number is:", result)
Output result
The largest number is: 23
If you need to find the smallest item, you can usePython min()Function.