Python map & reduce 以及lambda匿名函数

原创转载请注明出处:http://agilestyle.iteye.com/blog/2330300

map()

map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

使用map实现一个f(x) = x * x的功能

def f(x):
    return x * x


m = map(f, list(range(1, 10)))
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
print(list(m))

另外可以使用lambda函数简化

# [1, 4, 9, 16, 25, 36, 49, 64, 81]
print(list(map(lambda x: x * x, list(range(1, 10)))))

Console Output

Note:

可以看出 

lambda x: x * x

实际上就是:

def f(x):
    return x * x

把list中的所有数字转为字符串

# ['1', '2', '3', '4', '5', '6', '7', '8', '9']
print(list(map(str, list(range(1, 10)))))

Console Output


 

reduce() 

reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) 

使用reduce对一个序列求和

from functools import reduce


def add(x, y):
    return x + y

# 55
print(reduce(add, list(range(1, 11))))
# 55
print(reduce(lambda x, y: x + y, list(range(1, 11))))

Console Output

把序列[1, 2, 3, 4, 5, 6, 7, 8, 9]变换成整数123456789

from functools import reduce


def fn(x, y):
    return x * 10 + y


# 123456789
print(reduce(fn, list(range(1, 10))))
# 123456789
print(reduce(lambda x, y: x * 10 + y, list(range(1, 10))))

Console Output

map()和reduce()整合,把str转换位int

from functools import reduce


def char2num(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]


# '13579' => 13579
print(reduce(fn, map(char2num, '13579')))
# '13579' => 13579
print(reduce(lambda x, y: x * 10 + y, map(char2num, '13579')))


def str2int(s):
    def fn(x, y):
        return x * 10 + y

    def char2num(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

    return reduce(fn, map(char2num, s))


print(str2int('13579'))

Console Output


 

参考资料:

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317852443934a86aa5bb5ea47fbbd5f35282b331335000 


  


  

猜你喜欢

转载自agilestyle.iteye.com/blog/2330300