内建函数:print(dir(__builtin__))
>>> ...
1:map函数:
a=map(lambda x:x*x+1,[1,2,3,4])
print(list(a))
a=map(lambda x:x*x+1,range(0,10,2))
print(list(a))
a=map(lambda x,y:x*y+1,range(5),range(5,10,1))
print(list(a))
2:filter函数:
a=filter(lambda x:x%2,range(5))
print(list(a))
def foo(x):
if x>5:
return x
a=filter(foo,range(10))
print(list(a))
from functools import reduce
a=reduce(lambda x,y:x+y,range(5))
print(a)
3:reduce:
from functools import reduce
a=reduce(lambda x,y:x+y,range(5))
print(a)
def foo(x,y):
return x+y
a=reduce(foo,range(5))
print(a)
练习:
#1.使用map完成,计算1到9所有的数字的平方,并且把每个数字转为字符串
a=map(str,map(lambda x:x*x,range(10)))
print(list(a))
#2.使用reduce完成,把列表里的数字变换成整数,比如[1, 3, 5, 7, 9]变成13579
from functools import reduce
def counter(x,y):
return x*10+y
a=reduce(counter,range(5))
print(a)
# 3.去除列表中带4的手机号
nums=['18303517744', '15020030417', '15088931331', '15906878938', '13646514938', '13706636314', '18867793298', '13739742666', '15731102345', '13859652222', '18232102678', '13601261337', '15231099666', '18337728521', '15203802168', '18331758666', '18736599499', '13930109099', '15738888289', '15738888538', '15738888576', '15738888697', '15738888963', '13797904444', '15243191111', '18405311888', '18405312888', '13791080000', '13791090000', '13908376207', '13908335110', ]
for i in nums:
tmp=i.find("4",10)
print(tmp)
# find方法,当前i中没有“4”这个字符 则返回-1
a=filter(lambda x:x.find("4",0)==-1,nums)
print(list(a))
2023-04-27
网友评论