map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。
# 1、调用function函数,返回一个list
>>> def add100(x):
return x+100
>>> hh = [11,22,33]
>>> map(add100,hh)
[111, 122, 133]
# 2、多个参数之间的并行运算
>>> def abc(a,b,c):
return a*10000+b*100+c
>>> list1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]
>>> map(abc,list1,list2,list3)
[114477, 225588, 336699]
# 3、第一个函数为None时,按序输出
>>> list1 = [11,22,33]
>>> map(None, list1)
[11, 22, 33]
>>> list1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]
>>> map(None,list1,list2,list3)
[(11, 44, 77), (22, 55, 88), (33, 66, 99)]
# 4、列表推导式
>>> def add100(x):
return x+100
>>> list1 = [11,22,33]
>>> map(add100,list1)
[111, 122, 133]
>>> [add100(i) for i in list1]
[111, 122, 133]
>>>
>>> [abc(a,b,c) for a in list1 for b in list2 for c in list3]
[114477, 114488, 114499, 115577, 115588, 115599, 116677, 116688, 116699, 224477, 224488, 224499, 225577, 225588, 225599, 226677, 226688, 226699, 334477, 334488, 334499, 335577, 335588, 335599, 336677, 336688, 336699]
>>>
>>> result = []
>>> for a in list1:
for b in list2:
for c in list3:
result.append(abc(a,b,c))
>>> result
[114477, 114488, 114499, 115577, 115588, 115599, 116677, 116688, 116699, 224477, 224488, 224499, 225577, 225588, 225599, 226677, 226688, 226699, 334477, 334488, 334499, 335577, 335588, 335599, 336677, 336688, 336699]
>>>
# 5、map()作为高阶函数,事实上它把运算规则抽象
# 把这个list所有数字转为字符串
>>> map(str,[1,2,3,4,5])
['1', '2', '3', '4', '5']