English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemples de map() en Python

Python built-in functions

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, ...)

paramètres de carte()

  • fonction-carte()将Iterable(iterable) to each item of this function.

  • iterable iterable items

You can also pass multipleIteration (iterable)Passed to the map() function.

map() return value

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.

Example1:How does map() work?

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.

Example2:How to use lambda function in map()?

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.

Example3:Using Lambda to pass multiple iterators to map()

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]

Python built-in functions