Python老男孩 day16 函数(八) map函数

https://www.cnblogs.com/linhaifeng/articles/6113086.html

——————————————————————————————————————

1.Map函数

#实现列表每个数字变为它的平方

array=[1,3,4,71,2]

ret=[]

for i in array:
    ret.append(i**2)

print(ret)

 运行结果:

[1, 9, 16, 5041, 4]

#如果我们有一万个列表,那么你只能把上面的逻辑定义成函数

def map_test(array):
    ret=[]
    for i in array:
        ret.append(i**2)
    return ret

print(map_test(array))

 运行结果:

[1, 9, 16, 5041, 4]

 #如果我们的需求变了,不是把列表中每个元素都平方,还有加1,减1,那么可以这样

def add_num(x):
    return x+1

def map_test(func,array):
    ret=[]
    for i in array:
        ret.append(func(i))
    return ret

print(map_test(add_num,array))
#可以使用匿名函数
print(map_test(lambda x:x-1,array))

 运行结果:

[2, 4, 5, 72, 3]
[0, 2, 3, 70, 1]

#map(func,iter) 第一个参数可以是lambda,也可以是函数;第二个参数为可迭代对象

array=[1,3,4,71,2]

res=map(lambda x:x-1,array)

print(list(res))

运行结果:
[0, 2, 3, 70, 1]      #结果与上面我们自己写的map_test实现的一样


msg='linhaifeng'
print(list(map(lambda x:x.upper(),msg)))

运行结果:
['L', 'I', 'N', 'H', 'A', 'I', 'F', 'E', 'N', 'G']

 #上面就是map函数的功能,map得到的结果是可迭代对象

2.filter函数

需求:取出不带sb的人名

movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']

def filter_test(array):
    ret=[]
    for p in array:
        if not p.startswith('sb'):
               ret.append(p)
    return ret

res=filter_test(movie_people)
print(res)

运行结果:
['linhaifeng']

优化版:

movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']

def sb_show(n):
    return n.endswith('sb')

def filter_test(func,array):
    ret=[]
    for p in array:
        if not func(p):
               ret.append(p)
    return ret

res=filter_test(sb_show,movie_people)
print(res)

运行结果:
['linhaifeng']

最终版:

movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']

思路:
# def sb_show(n):
#     return n.endswith('sb')
#--->lambda n:n.endswith('sb')

def filter_test(func,array):
    ret=[]
    for p in array:
        if not func(p):
               ret.append(p)
    return ret

res=filter_test(lambda n:not n.endswith('sb'),movie_people)
print(res)

运行结果:
['linhaifeng']

filter函数

movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
print(filter(lambda n:not n.endswith('sb'),movie_people)) res=filter(lambda n:not n.endswith('sb'),movie_people)
print(list(res))

运行结果:
<filter object at 0x0000021842EFEB00>
['linhaifeng']

猜你喜欢

转载自www.cnblogs.com/zhuhemin/p/9116069.html
今日推荐