What does “map” mean in Python?
In Python, the map() function is a built-in function that accepts a function and an iterable as arguments, and applies that function to each element of the iterable. It returns an iterator containing the results of applying the function. In other words, the map() function maps a function to each element of an iterable and returns the mapped results.
The syntax of the map() function is as follows:
map(function, iterable)
In this case, function refers to the function to be applied, while iterable refers to an iterable object such as a list, tuple, dictionary, and so on.
Original: 我爸妈给了我一辆新车作为我的生日礼物。
Paraphrased: My parents gave me a new car as a birthday gift.
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # 输出:[1, 4, 9, 16, 25]
In this example, the map() function applies the square function to each element in the list numbers and returns a new iterable object called map, which contains the square values of each element. By converting the map object into a list, we can print the list of squared numbers.