call 迭代器 函数名 recent last style 元素 param
map()函数主要功能是对批量的元素进行相同的操作时可以大幅度的缩减代码。
map函数参数详解:
map(param1,param2,***)
param1:函数名 ,要对批量元素进行处理的function
param2~paramX:可迭代对象,(列表,元祖,迭代器...换句话说:能执行 for x in param:语句的都可以)
map只有两个参数时:
例如:
- >>> def function(x):
- ... return x*x
- ...
- >>> list1 = [1,2,3]
- >>> map(function,list1)
- [1, 4, 9]
- >>>
map参数为多个时:
需要注意的是:map参数的个数 与function参数个数的关系:map参数个数为x个,function个数为x-1个,否则会报错
例如(出错的情况):
- >>> def function(x):
- ... return x*x
- ...
- >>> list1 = [1,2,3]
- >>> list2 = [4,5,6]
- >>> list3 = [7,8,9]
- >>> map(function,list1,list2,list3)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: function() takes exactly 1 argument (3 given)
正确的用法应该是:
- >>> def function(x,y,z):
- ... return x+y+z
- ...
- >>> list1 = [1,2,3]
- >>> list2 = [4,5,6]
- >>> list3 = [7,8,9]
- >>> map(function,list1,list2,list3)
- [12, 15, 18]
Python 进阶 之 map()函数
来源: http://www.bubuko.com/infodetail-2282039.html