函数式编程

lambda

lambda函数的使用方法:

         在lambda后面直接跟变量;

         变量后面是冒号;

         冒号后面是表达式,表达式计算结果就是本函数的返回值。

lambda表达式的公式:

         lambda  arg1, arg2,…,argN:expression  using  arguments

         lambda表达式不能包含命令,包含的表达式不能超过一个。不要试图向lambda表达式中塞入太多的东西,因为lambda表达式存在的意义本身就是使编程更简洁。

>>> num_list = [1, 2, 3, 4, 5, 6, 7]
>>> lamb = lambda x: x+3    # 定义lambda表达式,实现+3的操作,结果返回冒号后表达式计算的结果
>>> num = []
>>> for i in num_list:
...     num.append(lamb(i))    # lambda表达式赋给变量lamb后,直接用变量名传入参数
...
>>> num
[4, 5, 6, 7, 8, 9, 10]

>>> g = lambda x, y: x + y    # 定义了一个实现两个数相加的lambda表达式,并将其赋给变量g
>>> g(4, 12)    # 通过变量g向lambda表达式传入参数
16
>>> (lambda x, y: x * y)(3, 7)    # 直接在lambda表达式后传入参数,传参的方式类似于函数
21

>>> def test(a, b, func):
...     result = func(a, b)
...     print(result)
...
>>> test(11, 22, lambda x,y:x+y)    # 将匿名函数lambda表达式作为另外一个函数的参数传递
33

>>> func = input('请输入一个函数:')    # input将任何输入的内容都处理成字符串
请输入一个函数:lambda x, y: x + y    # 输入了一个lambda表达式
>>> func    # lambda表达式被处理成字符串
'lambda x, y: x + y'
>>> func = eval(func)    # 用eval将字符串转换成可执行的函数
>>> func    
<function <lambda> at 0x7fe3d643a8c8>
>>> test(22, 33, func)    # 函数作为参数传递给另外一个函数
55

lambda还可以不传参数,直接使用全局变量:
>>> x = 55    # 全局变量
>>> func = lambda : x + 50    # lambda表达式中没有参数
>>> func()    # 直接调用,不传参数
105

  lambda表达式也可以像普通函数那样,直接使用全局变量。


map

  map的使用:

    Help on class map in module builtins:

    class map(object)

     |  map(func, *iterables) --> map object    # 第二个参数是一个收集迭代对象的参数

     |                                    # 返回一个map对象

     |  Make an iterator that computes the function using arguments from

     |  each of the iterables.  Stops when the shortest iterable is exhausted.

  map()函数是python的一个内置函数,它的基本样式是:

                          map(func, seq)

         其中,func是一个函数对象,seq是一个序列对象。在执行的时候,序列对象中的每个元素,按照从左到右的顺序,依次被取出来,塞入到func函数里,作为func函数的参数。最后返回一个map对象,这个对象是迭代器。

         对map()函数主要理解以下几个要点:

                  对可迭代对象中的每个元素,依次应用function的函数(本质上就是一个for循环);

                  将所有结果返回一个map对象,这个对象是迭代器;

                  如果参数很多,则对那些参数并行执行function函数,就可以提升运行速度。

>>> num_list = [1, 2, 3, 4, 5, 6, 7]
>>> list(map(lambda x: x + 3, num_list))    # map第一个参数是一个函数,第二个参数是序列
[4, 5, 6, 7, 8, 9, 10]

  在应用中,map能实现的,也可以用其他方式实现:

>>> num_list = [1, 2, 3, 4, 5, 6, 7]
>>> squared = []
>>> for i in num_list:    # 普通for循环的方法
...     squared.append(i**2)
...
>>> squared
[1, 4, 9, 16, 25, 36, 49]
>>> def square(x): return x ** 2
...
>>> list(map(square, num_list))    # map+普通函数的方法
[1, 4, 9, 16, 25, 36, 49]
>>> list(map(lambda x: x + 2, num_list))    # map+lambda表达式的方法
[3, 4, 5, 6, 7, 8, 9]
>>> [i * 2 for i in num_list]    # 列表解析
[2, 4, 6, 8, 10, 12, 14]

  使用map使编程更简洁,提高性能:

>>> list1 = [1, 2, 3, 4, 5]
>>> list2 = [6, 7, 8, 9, 10]
>>> list3 = [11, 12, 13, 14, 15]    # 实现三个列表中对应位置元素相加
>>> list(map(lambda x, y, z: x + y + z, list1, list2, list3))    # 使用map更简洁,效率更高
[18, 21, 24, 27, 30]
>>> map(lambda x, y, z: x + y + z, list1, list2, list3)    # map返回的是一个map对象
<map object at 0x7f8aef83c828>

reduce

  首先声明:在python3中,reduce被移到了functools模块里了;在python2中尚在全局命名空间中。

  reduce的使用:

    >>> from functools import reduce    # reduce在functools模块里,需先导入

    >>> 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.

         reduce()的第一个参数是一个函数,第二个参数是序列类型的对象。它与map的区别有:map第二个参数可传入多个可迭代的对象,而reduce的第二个参数只能传入一个序列对象。map是上下运算;reduce是横着逐个元素进行运算。此外reduce还可指定第三个可选参数,用以指定reduce第一个参数的函数的起始值。

         使用reduce实现累加操作:

>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])    # 实现累加
15
>>> reduce(lambda x, y: x + y, list(range(1, 101)))    # 实现1-100的累加
5050
>>> reduce(lambda x, y: x + y, list(range(1, 101)), 2)    # 指定第三个可选参数作为函数的起始值
5052
>>> reduce(lambda x, y: x + y, list(range(1, 101)), 9)    # 函数的第二个值继续从序列中取得
5059
>>> reduce(lambda x, y: x + y, list(range(3, 101)))    # 实现3-100的累加
5047
>>> reduce(lambda x, y: x + y, list(range(3, 101)), 2)
5049

filter

  filter的使用:起到过滤的作用。

    Help on class filter in module builtins:

    class filter(object)

     |  filter(function or None, iterable) --> filter object    # 返回一个filter对象

     |

     |  Return an iterator yielding those items of iterable for which function(item)

     |  is true. If function is None, return the items that are true.

         filter的第一个参数是一个条件表达式或者为空,第二个参数是一个可迭代对象。

>>> numbers = range(-1, 5)
>>> list(filter(lambda x: x > 0, numbers))    # 条件为真时,返回满足条件的值
[1, 2, 3, 4]
>>> list(filter(lambda c: c != 't', 'python'))
['p', 'y', 'h', 'o', 'n']

zip

  zip的使用:

    >>> help(zip)

    Help on class zip in module builtins:

    class zip(object)

     |  zip(iter1 [,iter2 [...]]) --> zip object    # 传入至少一个可迭代的对象

     |                                                                      # 返回一个zip对象

     |  Return a zip object whose .__next__() method returns a tuple where

     |  the i-th element comes from the i-th iterable argument.  The .__next__()

     |  method continues until the shortest iterable in the argument sequence

     |  is exhausted and then it raises StopIteration.


>>> colors = ['red', 'green', 'blue']
>>> values = [234, 12, 89, 65]
>>> list(zip(colors, values))    # 将迭代对象中对应位置的值组成元组,返回zip对象
[('red', 234), ('green', 12), ('blue', 89)]    # zip自动进行匹配,抛弃不对应的项,以最短的为准

>>> dots = [(1, 2), (3, 4), (5, 6)]
>>> x, y = zip(*dots)    # 以分配参数的方式传入
>>> x
(1, 3, 5)
>>> y
(2, 4, 6)

>>> a = [1, 2, 3, 4, 5]
>>> b = [2, 2, 9, 0, 10]
>>> list(map(lambda value: max(value), zip(a, b)))
[2, 2, 9, 4, 10]


两个变量的值互换:

         方法一:通过一个中间变量完成。

>>> a = 12    # 实现变量a、b值互换
>>> b = 99
>>> c = 0    # 通过中间变量c来完成
>>> c = a
>>> a = b
>>> b = c
>>> a
99
>>> b
12

  方法二:python的特有方法。

>>> a = 12
>>> b = 99
>>> a, b = b, a
>>> a
99
>>> b
12

  方法三:通过数学运算

>>> a = 12
>>> b = 99
>>> a = a + b
>>> b = a - b
>>> a = a - b
>>> a
99
>>> b
12
原文地址:https://www.cnblogs.com/wgbo/p/9663110.html