Python入门 函数式编程

高阶函数

map/reduce

from functools import reduce

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

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

print(list(map(char2num, "12357")))

print(reduce(fn, map(char2num, "12357")))

编写成一个函数

from functools import reduce

digits = {'0':0, '1':1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}

def str2int(s):
    def fn(x,y):
        return x*10+y
    def str2num(s):
        return digits[s]
    return reduce(fn, map(str2num, s))

print(str2int("987654321"))

lambda表达式改写

from functools import reduce

digits = {'0':0, '1':1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}

def str2num(s):
    return digits[s]    

def str2int(s):
    return reduce(lambda x,y:x*10+y, map(str2num, s))

print(str2int("23718912739"))

filter 过滤

def odd(n):
    return n % 2 == 1;

print(list(filter(odd, range(10))))

参考文章

python高阶函数

猜你喜欢

转载自www.cnblogs.com/Draymonder/p/10667468.html