Python functional Programming Getting Started tutorial

Source: Internet
Author: User
Tags iterable
Introduction

Functional programming (functional programming) concept originated in Lisp, founded by John McCarthy in 1958, the idea of automatic garbage collection was first proposed, and this concept is now being used for reference by Python/java/ruby and other languages. To this day, Lisp has derived a variety of dialects. One of the great advantages of functional programming compared to object-oriented programming is that immutable data is not dependent on external data, and does not change the value of external data, which can greatly reduce the bugs in our code, and functional programming also allows us to use functions like variables. Python, as an object-oriented language, also provides support for functional programming, albeit not purely, and does not support tail-recursive optimizations.

Use of lambda

Lambda is an anonymous function, and reasonable use of lambda can not only reduce our code, but also better depict code logic, such as now we have a function like this.

>>> def f (x): ...    return x + x# call this function >>> F (2) 4

This function if we use LAMDA rewrite, as long as a line of code is enough.

# The x behind the lambda represents the parameter to be received by the lambda function, X + x represents the value to be returned by the lambda function >>> f = lambda x:x + x# can see that F is now also a function object >>> f<funct Ion __main__.<lambda>># call lambda function >>> F (2) 4

Use of Map

Map (function, iterable) receives two parameters, the first parameter represents the receipt of a function, and the second parameter represents an object that receives a iteralbe type, such as list.

The principle of the map function is: 1. Each time a parameter is taken from the iterable, 2. Pass this parameter to our function, 3. Then the value returned by the function is added to a list (this is not accurate, just to help you understand, I will explain later). After all the iterable objects have been traversed, the map returns the list to our callers. Let's take a look at the usage of the map directly from the example.

Example1

# or use the lambda example above us >>> function = lambda x:x + x# to define a Iterable object list (lists) >>> iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]# function fucntion each time a parameter x is taken from the iterable, then function returns the value of X + x, # and adds the return value to a new list, and so on iterable traversal, the map will return the new list. >>> v = map (function, iterable) # Note that the above statement is not accurate, just to help you understand, in fact, the map returned is a map object, not list>>> V<map at 0x7fcb56231588># but we can call the built-in list function to convert the map to a list to get the results we want >>> list (v) [2, 4, 6, 8, 10, 12, 14, 16, 18]

Example2

For the second parameter of map, we can also pass a list of functions, which means that there are multiple function objects in the middle of the list.

>>> multiply = Lambda x:x * x>>> add = lambda x:x + x>>> Funcs = [Multiply, add]>>> List (Map (lambda f:f (1), Funcs)) [1, 2]

Use of reduce

As with map, reduce (function, iterable) also receives two parameters, the first parameter represents the receipt of a function, and the second parameter represents an object that receives a iteralbe type, such as list. But the difference is that this function in reduce has to receive two parameters, so let's look at the usage of reduce by asking for an example of a list summation.

From Functools import reduce# uses lambda to define a function that takes two parameters and then returns the sum of two parameters >>> function = lambda x, y:x+y>>> Iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]# function functions each receive two arguments, except for the first time taking an element from the iterable as a parameter # Another parameter is taken from the value returned by the last function >>&G T Reduce (function,  iterable) 45

Use of filter

Similar to Map/reduce, filter (function, iterable) also receives two parameters at a time, one parameter is a function, the other is a Iterable object, as can be seen from the name, filter is used for filtering the Iterble object, For example, list.

It does this by removing an element from the Iterable object for use in our function, preserving the element if the function returns True, or deleting the element if it returns false. Let's look at the use of filter using an example.

# defines a function if the received character S is empty, then returns false if non-null, then returns 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 ']

Decorative Device

An adorner (decorator) is an advanced Python syntax. Adorners can be used to process a function, method, or class. Proper use of adorners can reduce our code volume and improve program readability, and in many Python frameworks, such as Django, we can see a lot of adorners.

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

Now we have the above two functions, respectively, for addition and multiplication, but now we feel that the function is not enough, we want to add some output statements before returning the result, in general, we want to refactor two functions, to the following.

>>> 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 adorners we can do the following, although we do not see the advantages of using adorners now, but if we want to add more than one print function, and besides add/multiply we have minus/divide and other functions, This time the power of the adorner is reflected, we can only modify a code, so that not only improve the readability of the program, but also for the future we refactor the code to save a lot of work.

def decorator (F):    def new_function (x, y):        print ("Input:", x, y)        return F (x, y)    return new_ Function@decoratordef Add (x, y):    return x + y@decoratordef multiply (x, y):    return x * y

The above is the content of the Python Functional Programming starter tutorial, more relevant content please follow topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.