D16-08 map函数
举例,列表自增1
num_l=[1,2,10,5,3,7]
def add_one(x):
return x+1
def map_test(func,array):
ret=[]
for i in num_l:
res = func(i)
ret.append(res)
return ret
print(map_test(add_one,num_l))
输出结果
[2, 3, 11, 6, 4, 8]
def map_test(func,array):
ret = [] #创建空列表
for i in num_l:
res = func(i) 给func的结果赋值
ret.append(res)
return ret
print(map_test(add_one,num_l))
输出结果
[2, 3, 11, 6, 4, 8]
将def 函数改为匿名函数
num_l=[1,2,10,5,3,7]
def add_one(x):
return x+1
lambda x:x+1
def map_test(func,array):
ret = []
for i in array:
res = func(i)
ret.append(res)
return ret
print(map_test(add_one,num_l))
print(map_test(lambda x:x+1,num_l))
输出结果一样
num_l=[1,2,10,5,3,7]
def add_one(x):
return x+1
lambda x:x+1
def map_test(func,array):
ret = []
for i in array:
res = func(i)
ret.append(res)
return ret
print(map_test(add_one,num_l))
print(map_test(lambda x:x+1,num_l))
print(map(lambda x:x+1,num_l))
print('内置函数函数map处理结果',map(lambda x:x+1,num_l)) #打印的结果为<map object at 0x000001396A5271D0>是可迭代类型,可以用for循环遍历
输出结果
[2, 3, 11, 6, 4, 8]
[2, 3, 11, 6, 4, 8]
<map object at 0x0000021D58AE70F0>
内置函数函数map处理结果 <map object at 0x0000021D58AE7128>
用map函数,map函数是典型的函数是编程,代码结构比较简洁,但易读性较差。
map的处理结果为可迭代对象,而list可以遍历对象打印成列表。
num_l=[1,2,10,5,3,7]
def add_one(x):
return x+1
lambda x:x+1
def map_test(func,array):
ret = []
for i in array:
res = func(i)
ret.append(res)
return ret
print(map_test(add_one,num_l))
print(map_test(lambda x:x+1,num_l))
print(map(lambda x:x+1,num_l))
print('内置函数函数map处理结果',map(lambda x:x+1,num_l)) #打印的结果为<map object at 0x000001396A5271D0>是可迭代类型,可以用for循环遍历
res = map(lambda x:x+1,num_l)
print(list(res))
print('传的是有名函数',list(map(add_one,num_l)))
输出结果
[2, 3, 11, 6, 4, 8]
[2, 3, 11, 6, 4, 8]
<map object at 0x00000218C6959128>
内置函数函数map处理结果 <map object at 0x00000218C6959160>
[2, 3, 11, 6, 4, 8]
传的是有名函数 [2, 3, 11, 6, 4, 8]
msg = 'liupingtao' print(list(map(lambda x:x.upper(),msg))) 输出结果 ['L', 'I', 'U', 'P', 'I', 'N', 'G', 'T', 'A', 'O']

浙公网安备 33010602011771号