Python functional programming introductory tutorial
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 = ['AJ', ' ', 'Stussy', '', 'CLOT', 'FCB', None] >>> filter(function, iterable) <filter at 0x7fcb562319b0> >>> list(filter(function, iterable)) ['AJ', 'Stussy', 'CLOT', 'FCB']
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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
