python从0到1学习笔记

Python函数式编程

2018-08-22  本文已影响5人  三不小青年

# 闭包 

# 保存外层函数 环境

def clo_cur():

a =25

    b =1

    def cur(x):

result = a*x*x+b

return result

return cur

a =10  # 闭包会优先使用用包裹里面的数据

f = clo_cur()

print(f.__closure__)

print(f.__closure__[0].cell_contents)

print(f.__closure__[1].cell_contents)

print(type(f))

print(f(2))

# 闭包 函数+变量

# 保存上一级变量

def col_step_count():

count =0

    def step_count(number):

nonlocal count# 要指定不是本地变量,否则会报错

        new_count = count + number

count = new_count

return new_count

return step_count

f = col_step_count()

print(f.__closure__[0].cell_contents)

print(f(3))

print(f.__closure__[0].cell_contents)

print(f(5))

print(f.__closure__[0].cell_contents)

Lamaba匿名函数

print(f.__closure__[0].cell_contents)

# lambda paramaters: expression

f =lambda x,y : x+y

print(f(1,2))

Map

# map(def,*)

List_x = [1, 2, 3, 4, 5, 6, 7, 8, 9]

List_y = [1, 2, 3, 4, 5, 6, 7, 8, 9]

r =list(map(lambda x,y: x*x+y, List_x, List_y))

print(r)

Reduce

# reduce 用来做连续运算

from functoolsimport reduce

step = [(-1, 2), (0, 3), (1, 5)]

r = reduce(lambda x, y: (x[0]+y[0], x[1]+y[1]), step)

print(list(r))

Filter

# filter 过滤器,lambda 表达式(函数)返回bool,从而进行过滤

# 例 筛选出小写字母

alp = ['a', 'b', 'A', 'B']

r =filter(lambda x: x >'Z', alp)

print(list(r))

上一篇 下一篇

猜你喜欢

热点阅读