python map函数的用法
map函数是一个内置函数,它接受一个函数和一个可迭代对象作为参数,将函数应用于可迭代对象中的每个元素,并返回一个迭代器,该迭代器包含该函数应用于每个元素的结果。
语法: map(function, iterable, ...)
参数说明: function:要应用于 iterable 中的每个元素的函数。 iterable:要迭代的序列、集合、列表等。 ...:可选,可以提供多个 iterable。当提供多个 iterable 时,map 函数将并行地应用 function 到每个 iterable 的相应元素上,直到所有 iterable 耗尽。
示例: 将列表中的每个元素都平方并返回一个新的列表:
def square(x):
return x ** 2
lst = [1, 2, 3, 4, 5]
new_lst = list(map(square, lst))
print(new_lst) # [1, 4, 9, 16, 25]
将两个列表中的元素一一对应相加并返回一个新的列表:
lst1 = [1, 2, 3, 4, 5]
lst2 = [10, 20, 30, 40, 50]
new_lst = list(map(lambda x, y: x + y, lst1, lst2))
print(new_lst) # [11, 22, 33, 44, 55]
``
原文地址: https://www.cveoy.top/t/topic/eDtG 著作权归作者所有。请勿转载和采集!