py-day3-6 python map函数

## 求列表里元素的平方  (原始方法)
num_1=[1,2,13,5,8,9]
res =[]
for i in num_1:
    res.append(i**2)
print('打印结果:',res)

打印结果: [1, 4, 169, 25, 64, 81]

有多个列表求里面元素的平方 (定义成函数)
num_1=[1,2,13,5,8,9]
def test(array):
    res =[]
    for i in num_1:
        res.append(i**2)
    return res
end1 = test(num_1)
end2 = test(num_1)             # 以后用直接调用函数就可以了
print('打印结果:',end1)
print('打印结果:',end2)

打印结果: [1, 4, 169, 25, 64, 81]
打印结果: [1, 4, 169, 25, 64, 81]

提的需求就是功能,功能就要封装在函数里
num_1=[1,2,13,5,8,9]
def reduce_1(x):        # 定义自减1函数
    return x-1
def add_1(x):           # 定义自增1函数
    return x+1
def test(func,array):
    res =[]
    for i in num_1:
        ret=func(i)
        res.append(ret)
    return res
print('自增1的结果:',test(add_1,num_1))
print('自减1的结果:',test(reduce_1,num_1))

自增1的结果: [2, 3, 14, 6, 9, 10]
自减1的结果: [0, 1, 12, 4, 7, 8]

# 终极版本  最简单的.使用匿名函数同样可以做到
num_1=[1,2,13,5,8,9]
def test(func,array):
    res =[]
    for i in num_1:
        ret=func(i)
        res.append(ret)
    return res
print('自增1的结果:',test(lambda x:x+1,num_1))
print('自减1的结果:',test(lambda x:x-1,num_1))
print('平方的结果:',test(lambda x:x**2,num_1))
print('除2的结果:',test(lambda x:x/2,num_1))

自增1的结果: [2, 3, 14, 6, 9, 10]
自减1的结果: [0, 1, 12, 4, 7, 8]
平方的结果: [1, 4, 169, 25, 64, 81]
除2的结果: [0.5, 1.0, 6.5, 2.5, 4.0, 4.5]

内置函数map函数
num_1=[1,2,13,5,8,9]
def test(func,array):
    res =[]
    for i in num_1:
        ret=func(i)
        res.append(ret)
    return res
print('匿名函数的处理结果:',test(lambda x:x+1,num_1))

ret = map(lambda x:x+1,num_1)
print('内置函数map的处理结果:',list(ret))

匿名函数的处理结果: [2, 3, 14, 6, 9, 10]
内置函数map的处理结果: [2, 3, 14, 6, 9, 10]

map函数 还适用与自己设定的函数
num_1=[1,2,13,5,8,9]
def reduce_1(x):        # 定义自减1函数
    return x-1
def add_1(x):           # 定义自增1函数
    return x+1
def test(func,array):
    res =[]
    for i in num_1:
        ret=func(i)
        res.append(ret)
    return res
ret = map(reduce_1,num_1)
ret1 = map(add_1,num_1)
print('map处理自减1的结果:',list(ret))
print('map处理自加1的结果:',list(ret1))

map处理自减1的结果: [0, 1, 12, 4, 7, 8]
map处理自加1的结果: [2, 3, 14, 6, 9, 10]

map还以可以迭代其他对象
msg ='majunnihao'    #(例如小写转换成大写)
t = map(lambda x:x.upper(),msg)
print(list(t))

['M', 'A', 'J', 'U', 'N', 'N', 'I', 'H', 'A', 'O']

猜你喜欢

转载自www.cnblogs.com/majunBK/p/10441760.html