Home  >  Article  >  Backend Development  >  Python functional programming introductory tutorial

Python functional programming introductory tutorial

黄舟
黄舟Original
2017-02-04 16:42:271520browse

Introduction

Functional The concept of Programming (functional programming) first originated from LISP, founded by John McCarthy in 1958, who first proposed the concept of automatic garbage collection. This concept is now also used by many languages ​​​​such as Python/Java/Ruby. Today, LISP has spawned many dialects. Compared with object-oriented programming, one of the advantages of functional programming is Immutable Data (data is immutable) means that it does not rely on external data and does not change the value of external data. This idea can greatly reduce bugs in our code, and functional programming also supports us to use functions like variables. As an object-oriented language, Python also provides support for functional programming, although it is not that pure and does not support tail recursion optimization.

Use of lambda

lambda is an anonymous function. Proper use of lambda can not only reduce the amount of our code, but also better describe the code logic, such as now We have a function like the following.

>>> def f(x):
...    return x + x
# 
调用这个函数
>>> f(2)
4

If we rewrite this function using lamda, only one line of code is enough.

# 
lambda后面的x表示lambda函数要接收的参数,x + x表示lambda函数所要返回的值
>>> f = lambda x: x + x
# 
可以看到f现在也是一个函数对象
>>> f
<function __main__.<lambda>>
# 
调用lambda函数
>>> f(2)
4

Use of map

map(function, iterable) receives two parameters. The first parameter represents receiving a function, and the second parameter represents receiving an iteralbe type object, such as a list.

The principle of map function is: 1. Take out a parameter from iterable each time, 2. Pass this parameter to our function, 3. Then add the value returned by the function to a list (this statement is not accurate, just to help everyone understand, I will explain it later) . After all iterable objects have been traversed, map returns the list to our caller. Let's learn how to use map directly through examples.

example1

# 
还是用我们上面那个lambda的例子
>>> function = lambda x: x + x
# 
定义一个iterable对象list(列表)
>>> iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 
函数fucntion每次从iterable中取出一个参数x,然后function返回x + x的值,
# 
并将返回值加入一个新建的list,等将iterable遍历完,map就将这个新建的list返回。
>>> v = map(function, iterable)
# 
注意上面的说法并不准确,只是为了帮助大家理解,其实map返回的是一个map对象,并不是list
>>> v
<map at 0x7fcb56231588>
# 
但是我们可以调用内建的list函数将map转换成一个list来得到我们想要的结果
>>> list(v)
[2, 4, 6, 8, 10, 12, 14, 16, 18]

example2

For the second parameter of map, we can also pass a set of function lists, which means that the list contains multiple function objects.

>>> multiply = lambda x: x * x
>>> add = lambda x: x + x
>>> funcs = [multiply, add]
>>> list(map(lambda f: f(1), funcs))
[1, 2]

Usage of reduce

The same as map, reduce(function, iterable) also receives two parameters. The first parameter represents receiving a function, and the second parameter represents receiving an iteralbe type object, such as a list. But the difference is that the function in reduce must receive two parameters. Let's learn how to use reduce through the example of finding the cumulative sum of a list.

from functools import reduce
# 
使用lambda定义一个函数,函数的作用是接收两个参数,然后返回两个参数之和
>>> function = lambda x, y: x+y
>>> iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 
函数function每次接收两个参数,除第一次外每次从iterable中取一个元素作为一个参数
# 
另外一个参数取自上一次function返回的值
>>> reduce(function,  iterable)
45

Usage of filter

is similar to map/reduce, filter(function, iterable) also receives two parameters at a time, one parameter is a function, and the other parameter is an iterable object. As can be seen from the name, filter is used to filter iterable objects, such as list (list).

The principle is to take out an element from the iterable object each time and apply it to our function. If the function returns True, the element will be retained. If the function returns False, the element will be deleted. Let's take a look at the usage of filter through an example.

# 
定义一个函数,如果接收的字符s为空,那么返回False,如果为非空,那么返回True
>>> function = lambda s : s and s.strip()
>>> iterable = [&#39;AJ&#39;, &#39; &#39;, &#39;Stussy&#39;, &#39;&#39;, &#39;CLOT&#39;, &#39;FCB&#39;, None]
>>> filter(function, iterable)
<filter at 0x7fcb562319b0>
>>> list(filter(function, iterable))
[&#39;AJ&#39;, &#39;Stussy&#39;, &#39;CLOT&#39;, &#39;FCB&#39;]

Decorator

Decorator (decorator) is an advanced Python syntax. Decorators can process a function, method or class. Reasonable use of decorators can reduce the amount of our code and improve the readability of the program. In many Python frameworks, such as Django, we can see a large number of decorators.

>>> def add(x, y):
...     return x + y
... 
>>> def multiply(x, y):
...     return x * y
...

Now we have the above two functions, which are used for addition and multiplication respectively, but now we feel that the function is not enough and want to add some output statements before returning the result. Generally speaking, we need to reconstruct the two functions , just like this.

>>> def add(x, y):
...     print("input:", x, y)
...     return x + y
... 
>>> def multiply(x, y):
...     print("input:", x, y)
...     return x * y
...

If we use a decorator, we can do as follows. Although it seems that there is no advantage in using a decorator in our current situation, if we want to add more than one printing function, and in addition to add/multiply We also have functions such as minus/divide. At this time, the power of the decorator is reflected. We only need to modify one code. This not only improves the readability of the program but also saves us the trouble of reconstructing the code in the future. A lot of work.

def decorator(F):
    def new_function(x, y):
        print("input:", x, y)
        return F(x, y)
    return new_function
@decorator
def add(x, y):
    return x + y
@decorator
def multiply(x, y):
    return x * y

The above is the content of the Python functional programming introductory tutorial. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn