English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La fonction carte() applique une fonction donnée à chaque élément d'un itérable (liste, tuple, etc.) et retourne une liste de résultats.
La syntaxe de carte() est :
carte(function, iterable, ...)
fonction-carte()将Iterable(iterable) to each item of this function.
iterable iterable items
You can also pass multipleIteration (iterable)Passed to the map() function.
The map() function applies the given function to each item of the iterable and returns the result list.
Then, the return value of map() (map object) can be passed tolist()(Creating a list),set()(Creating a set) and other functions.
def calculateSquare(n): return n*n numbers = (1, 2, 3, 4) result = map(calculateSquare, numbers) print(result) # Convert map object to set collection numbersSquare = set(result) print(numbersSquare)
When running the program, the output is:
<map object at 0x7f722da129e8> {16, 1, 4, 9}
In the above example, each item of the tuple is squared.
Since map() expects to pass a function, lambda functions are usually used when using the map() function.
Lambda functions are nameless anonymous functions. Learn aboutPython lambda functionMore information.
numbers = (1, 2, 3, 4) result = map(lambda x: x*x, numbers) print(result) # Convert map object to set collection numbersSquare = set(result) print(numbersSquare)
When running the program, the output is:
<map 0x7fafc21ccb00> {16, 1, 4, 9}
This example andExample1It is functionally equivalent.
In this example, corresponding items of two lists are added.
num1 = [4, 5, 6] num2 = [5, 6, 7] result = map(lambda n1, n2: n1+n2, num1, num2) print(list(result))
When running the program, the output is:
[9, 11, 13]