Python学习手册——函数(2)

纸上得来终觉浅,绝知此事要躬行!

递归函数

递归函数:直接或间接调用自身以进行循环的函数。

如下是个使用递归函数的加法+合并的多态运算函数,对任意可迭代对象都有效。

def mysum(L):
    first,*rest=L
    return first if not rest else first+mysum(rest)

不过,某些地方使用循环语句往往更简单,更节省运算时间。

sum = 0
for x in L:sum += x

递归可以遍历任意形状的结构,而这些可能就不是简单循环可以做到的。

def mysum(L):
    tot = 0
    for x in L:
        print(x)
        if not isinstance(x,list):
            tot += x
        else:
            tot += mysum(x)
    return tot
mysum([1,2,3,[1,2]])

函数属性

函数对象不仅限于系统定义属性,可以向函数附加任意的用户自定义的属性。这样的属性可以用来直接把状态信息附加到函数对象,可以在函数自身的任何地方访问,而不必使用全局、非本地和类等其他技术。这种变量的名称对于一个函数来说是本地的,但是其值在函数退出后仍然保留。

Py3中的函数注解

在Py3中,也可以给函数对象附加注解信息:与函数参数和结果相关的任意的用户定义的数据。注解出现的时候只是直接附加到函数对象的__annotations__属性以供其他用户使用。

def func(a:int,b:"second paratmeter",c)-> "求和":
    return a+b+c

func.__annotations__
Out[23]: {'a': int, 'b': 'second paratmeter', 'return': '求和'}

匿名函数:lambda

lambda argument1,argument2,...,argumentN:expression using arguments

lambda表达式创建了一个之后能够调用的函数,返回一个函数而不是将这个函数赋值给一个变量名(def的功能)。下面的表达式就创建了一个实现3个参数连乘的函数:

f = lambda x,y,z:x*y*z
f(2,4,5) # 40

In[31]:(lambda x,y,z:x*y*z)(2,4,"a")
Out[31]: 'aaaaaaaa'

函数式编程工具:map、filter和reduce

函数式编程:对序列应用一些函数的工具。包括,序列映射map,基于某一测试函数过滤元素filter,对每队元素都应用函数并运行到最后结果,……

程序对列表和其它序列常常要做的就是对每一个元素进行一个操作并把其结果集合起来。map(func,list)对list每个元素执行func函数操作,得到一个可迭代对象,Py3中使用list调用可以生成结果列表。

每一步,reduce传递当前的结果以及列表下一个元素,传给列出的函数: reduce(function, sequence[, initial]) -> value

pow(3,4)
# 81
list(map(pow,[1,2,3],[2,3,4]))
# [1, 8, 81]


list(filter(lambda x:x > 0,range(-5,5)))
# [1, 2, 3, 4]

from functools import reduce
reduce((lambda x,y:x+y),[1,2,3,4,5])
# 15

 help(map):

class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

 help(filter):

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

 help(reduce):

Help on built-in function reduce in module _functools:

reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值