1-高阶函数

  变量可以指向函数。   def add(x, y, f): 例如f参数为函数

编写高阶函数,就是让函数的参数能够接收别的函数。

Python内建了map()reduce()高阶函数。

1.1 将list每项相乘

def f(x):
return x*x
r = map(f, [1,2,3,4,5,6,7])
list(r) #[1, 4, 9, 16, 25, 36, 49] 每个变量的平方

1.2 把int转成字符串

list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) #把int转成字符串

1.3 把str转换为int的函数:

from functools import reduce
def fn(x, y):
return x * 10 + y def char2num(s):
digits = {'': 0, '': 1, '': 2, '': 3, '': 4, '': 5, '': 6, '': 7, '': 8, '': 9}
return digits[s] print(reduce(fn, map(char2num, '')))把str转换为int的函数:

1.4 filter使用

def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A','B ','',None,'C',' ']))

1.5 sorted使用

print(sorted([1,22,33,21,8])) #默认排序
print(sorted(['a','Z','B','c'],key=str.lower)) #按小写排序
print(sorted(['a','Z','B','c'],key=str.lower,reverse=True)) #按小写反向排序 def my_Sorted(item):
return item[0]
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
sorted(L,key=my_Sorted) #自定义的排序

1.6 闭包

def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs f1, f2, f3 = count() # 9 9 9 a,b,c = [1,2,3] #a=1,b=2,c=3

1.7 匿名函数  如: f= lambda x: x*x

list(map(lambda x: x*x, [1,2,3,4,5,6,7,8,9]))#[1, 4, 9, 16, 25, 36, 49, 64, 81]

1.8 装饰器 (装饰现有函数,返回一个新的函数。)

import functools
def log(func):
@functools.wraps(func) #相当wrapper.__name__ = func.__name__
def wrapper(*args,**kw):
print("call %s():" % func.__name__);
return func(*args, **kw)
return wrapper
@log
def now():
print('2018-05-11')
now() #相当 now = log(now)

带参装饰器

import functools
def log1(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s:' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator @log1('exceue')
def now1():
print('2018-5-5')
now1() #now = log('execute')(now)
#我们来剖析上面的语句,首先执行log('execute'),返回的是decorator函数,
#再调用返回的函数,参数是now函数,返回值最终是wrapper函数。

1.9 偏函数(通过设定参数的默认值,可以降低函数调用的难度。而偏函数也可以做到这一点)

int('',base=2) #结果23, 以2进行进行转换

import functools
int2 = functools.partial(int, base=2)#自定义的偏函数
print(int2('')) #结果23,

python-4函数式编程的更多相关文章

  1. python基础-函数式编程

    python基础-函数式编程  高阶函数:map , reduce ,filter,sorted 匿名函数:  lambda  1.1函数式编程 面向过程编程:我们通过把大段代码拆成函数,通过一层一层 ...

  2. 可爱的 Python : Python中函数式编程,第一部分

    英文原文:Charming Python: Functional programming in Python, Part 1 摘要:虽然人们总把Python当作过程化的,面向对象的语言,但是他实际上包 ...

  3. Python的函数式编程: map, reduce, sorted, filter, lambda

    Python的函数式编程 摘录: Python对函数式编程提供部分支持.由于Python允许使用变量,因此,Python不是纯函数式编程语言. 函数是Python内建支持的一种封装,我们通过把大段代码 ...

  4. python 10函数式编程

                                                                               函数式编程 函数是Python内建支持的一种封装, ...

  5. python之函数式编程

    python提供了支持函数式编程的简单机制: 1. map函数 2. filter函数 3. reduce函数. 典型的M/R计算模型. 但还是有点简单...

  6. 可爱的 Python : Python中函数式编程,第二部分

    英文原文:Charming Python: Functional programming in Python, Part 2,翻译:开源中国 摘要:  本专栏继续让David对Python中的函数式编 ...

  7. python专题-函数式编程

    函数式编程是使用一系列函数去解决问题,按照一般编程思维,面对问题时我们的思考方式是"怎么干",而函数函数式编程的思考方式是我要"干什么". 至于函数式编程的特点 ...

  8. Python进阶 函数式编程和面向对象编程等

    函数式编程 函数:function 函数式:functional,一种编程范式.函数式编程是一种抽象计算机的编程模式. 函数!= 函数式(如计算!=计算机) 如下是不同语言的抽象 层次不同 高阶函数: ...

  9. 【python】函数式编程

    No1: 函数式编程:即函数可以作为参数传递,也可以作为返回值  No2: map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的 ...

  10. python,函数式编程

    函数式编程: 特点:允许传递的参数是函数,且允许返回一个函数. 由于Python允许使用变量,因此,Python不是纯函数式编程语言,同样的输入可能输出不同,有副作用.纯函数式编程语言没有变量,输入和 ...

随机推荐

  1. android错误整理

    1.Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientat ...

  2. Centos 6/RHEL disable the IPv6 module.

    http://minimallinux.blogspot.com/2013/07/centos-6rhel-disable-ipv6-module.html IPv6 was introduced t ...

  3. C#实现屏幕指定区域截屏

    //string Opath = @"C:/Picture";            //if (Opath.Substring(Opath.Length - 1, 1) != @ ...

  4. JSON:json_encode函数不能获取属性原因及解决方案

    json_encode()是个解析json数据的函数,但是这个函数可以有两个参数 形式: json_decode ( string  $json,  ture || false )   第一个参数传字 ...

  5. myeclipse 10 创建webservice

    java 快捷创建webservice 收集一下,方便一下查阅 详情去看一下这个老哥,里面写得非常详细: http://hyan.iteye.com/ -- http://www.cnblogs.co ...

  6. April 13 2017 Week 15 Thursday

    Happiness takes no account of time. 幸福不觉光阴过. Do you know the theory of relativity? If you know about ...

  7. 如何用代码填充S/4HANA销售订单行项目的数量字段

    我的任务是用代码生成S/4HANA销售订单(Sales Order)的行项目,并且填充对应的quantity(数量)值. 最开始我用了下面的代码,把quantity的值写入item字段target_q ...

  8. Uva 11572 唯一的雪花

    题目链接:https://uva.onlinejudge.org/external/115/11572.pdf 题意:找到一个尽量长的连续子序列 Al ~ AR ,使得该序列没有相同的元素. 分析:枚 ...

  9. PHP精度问题

    PHP 为任意精度数学计算提供了二进制计算器(Binary Calculator),它支持任意大小和精度的数字,以字符串形式描述 bcadd — 加法bccomp — 比较bcdiv — 相除bcmo ...

  10. 剑指offer49 把字符串转换成整数

    这个代码会报错 class Solution { public: ,kinvalid}; int now_status = kvalid; int StrToInt(string str) { now ...