map函数

118 阅读1分钟

map函数是python中的内置函数,作用是将函数作用于可迭代对象的每个元素,再返回可迭代对象

map(function, iterable): 其中:

  • function 是要应用于每个元素的函数。
  • iterable 是一个可迭代对象,例如列表、元组、集合等。

map() 函数将 function 应用于 iterable 中的每个元素,并返回一个迭代器,该迭代器包含了通过函数处理得到的结果。

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]