Python map() 函数:应用函数于可迭代对象
在 Python 中,'map()' 函数的作用是将一个函数应用于一个或多个可迭代对象的所有元素,并返回一个包含应用函数后的结果的迭代器。具体来说,'map()' 函数将函数应用于可迭代对象的每个元素,并将结果作为迭代器返回。
例如,可以使用 'map()' 函数将一个函数应用于一个列表的所有元素,如下所示:
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]
在这个例子中,'map(square, numbers)' 对列表 'numbers' 中的每个元素应用了函数 'square()',并返回一个包含应用函数后的结果的迭代器 'squared_numbers'。最后,通过 'list()' 函数将迭代器转换为列表并打印出来。
'map()' 函数还可以接受多个可迭代对象作为参数,并将每个可迭代对象的相应元素作为参数传递给函数。如果可迭代对象的长度不一致,则 'map()' 函数会在最短的可迭代对象耗尽时停止。
除了函数本身,'map()' 函数还可以接受 lambda 函数作为参数,以便在不需要定义独立函数的情况下进行操作。例如:
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))
输出结果为:[1, 4, 9, 16, 25]
原文地址: https://www.cveoy.top/t/topic/lAoA 著作权归作者所有。请勿转载和采集!