map函数的语法如下:
map(function, iterable, ...)
其主要作用,就是对迭代对象中每一个元素,利用function函数做一次运算,然后然后将返回结果为了一个新的可迭代对象。自己也可以写这样一个map函数。
1 def fun(x): 2 return x * x 3 def another_map(l): 4 for i in l: 5 yield fun(i) 6 7 input = [1, 2, 3] 8 9 print('-'*20 + 'another map defined by me' +'-'*20 ) 10 output = another_map(input) 11 print(output) 12 for x in output: 13 print(x) 14 15 print('-'*20 + 'map function' +'-'*20 ) 16 for x in map(fun, input): 17 print(x)
对应的输出结果如下:
1 --------------------another map defined by me-------------------- 2 <generator object another_map at 0x0000000004EAA360> 3 1 4 4 5 9 6 --------------------map function-------------------- 7 1 8 4 9 9
既然已经有内置的函数了,我们就不要再去造一个轮子了。。。以前不知道这个函数,自己写了不少额外的轮子,想起来真的很汗颜。。。
看来还是要多多学些。