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)!

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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

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

SublimeText3 Chinese version
Chinese version, very easy to use