匿名函数和map()
1 num=[1,2,5,9,8]
2 def add(x):#lambda x:x+1
3 return x+1
4 def sub(x):#lambda x:x-1
5 return x-1
6 def squ(x):#lambda x:x**2
7 return x**2
8 def map_test(func,x):
9 array = []
10 for i in num:
11 res = func(i)
12 array.append(res)
13 return array
14 # res = map_test(add,num)
15 print(map_test(lambda x:x+1,num))
16 print(map_test(lambda x:x-1,num))
17 print(map_test(lambda x:x**2,num))
运行结果:
[2, 3, 6, 10, 9]
[0, 1, 4, 8, 7]
[1, 4, 25, 81, 64]
Process finished with exit code 0
1 num=[1,2,5,8,15]
2 def map_test(func,x):
3 array=[]
4 for i in x:
5 res=func(i)
6 array.append(res)
7 return array
8 ret = map_test(lambda x:x+1,num)
9 ret2=map_test(lambda x:x**2,num)
10 print(ret)
11 print(ret2)
运行结果:
[2, 3, 6, 9, 16]
[1, 4, 25, 64, 225]
Process finished with exit code 0
map()内置函数:
num=[1,2,5,8,15]
res = map(lambda x:x+1,num)#map函数的用法:map(处理方法,可迭代对象)
print(res)
print(list(res))
运行结果:
<map object at 0x01761930> # 地址值
[2, 3, 6, 9, 16]
Process finished with exit code 0
# 地址值
[2, 3, 6, 9, 16]
Process finished with exit code 0
<span style="color:#339966">str='dajdkaa'
map(lambda x:x.upper(),atr)#转换大小写
list(map(lambda x:x.upper(),atr))#转换为列表
print(map(lambda x:x.upper(),atr))#输出
</span>