❝在lambda章节中我们有讲到map函数。 map()内置函数将给定函数应用于可迭代的每一项,并返回一个迭代器对象。
❞
简单示例
nums = [1, 2, 3, 4, 5, 6] def func(x): return x+x nums = list(map(func,nums)) print(nums) # [2, 4, 6, 8, 10, 12]
❝此处你用for循环也可以,将每个值单独的迭代取值出来。
❞
等效写法
❝通俗点,自制map函数
❞
nums = [1, 2, 3, 4, 5, 6] def func(x): return x+x def mymap(fun,iterable): for i in iterable: yield fun(i) nums = list(mymap(func,nums)) print(nums)
❝仅用于加深理解。函数将的传值我就不在多的叙述了,yield方法,在迭代器中有讲到,后续会单独拉出来讲。
❞
带lambda的映射
❝这个lambda中也有提起。
❞
nums = [1, 2, 3, 4, 5, 6] res = map(lambda x: x+x, nums) print(list(res))
多个可迭代的映射
def func(x, y): return x + y nums = [1, 2, 3, 4, 5, 6] nums1 = [6, 7, 8, 9, 0, 1] res = map(func, nums, nums1) print(list(res)) # [7, 9, 11, 13, 5, 7]
映射多个函数
def func(x): return x * x def add(x): return x + x nums = [1, 2, 3, 4, 5, 6] for i in nums: value = list(map(lambda x: x(i),(add,func))) print(value) """ [2, 1] [4, 4] [6, 9] [8, 16] [10, 25] [12, 36] """
❝此处就不做多的概述了,因为,很多时候不会这么用。
❞