Learn Python's big topic and small function of 1

  • 2020-04-02 14:15:10
  • OfStack

We start with a big topic: programming paradigms. What is a programming paradigm? To paraphrase wikipedia:


Programming paradigm or programming paradigm Programming paradigm "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" For example: functional programming, program programming, object-oriented programming, instruction programming and so on for different programming paradigms. Programming paradigms provide (and determine) the programmer's view of program execution. For example, in object-oriented programming, programmers think of a program as a series of interacting objects, whereas in functional programming a program is considered a series of stateless function calculations.
 
Just as different groups in software engineering advocate different "methodologies", different programming languages advocate different "programming paradigms". Some languages are specifically designed for a particular paradigm (e.g Smalltalk and Java Supports object - oriented programming while Haskell and Scheme While functional programming is supported, there are other languages that support multiple paradigms (e.g Ruby , Common Lisp , Python and Oz ).
 
The relationship between programming paradigms and programming languages can be complex because a programming language can support multiple paradigms. For example, C++ At design time, procedural programming, object-oriented programming, and generic programming are supported. However, designers and programmers need to consider how to use these generic elements to build a program. One person can use it C++ Write a fully procedural program that another person can use C++ Write a pure object-oriented program, or even a program that mixes two paradigms.

No matter the officer is a beginner or a veteran, it is recommended to read the above paragraph carefully, no matter understand or do not understand, always can have a little feeling.

Here's a recommended article from the web: major programming paradigms

I've talked a lot about programming paradigms. What are we going to talk about today? Today I'm going to introduce you to a few small python functions borrowed from functional programming:

Filter, map, reduce, lambda, yield

With them, the biggest benefit is that the program is more concise; Without them, the program can be implemented in other ways, just a little more cumbersome. So, use what you can.

lambda

A lambda function, a one-line solution to a problem, sounds tempting. Here's an example:


>>> def add(x):     # Defines a function that increments the input variables 3, Then return the value of the increment
...     x +=3
...     return x
...
>>> numbers = range(10)
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  # There is one list I want each number to increase 3, And then output to a new one list In the >>> new_numbers = []
>>> for i in numbers:
...     new_numbers.append(add(i))  # call add() Function and append to list In the
...
>>> new_numbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

  In this case, add() is just an intermediate operation. Of course, the above example can be implemented in other ways. Such as:


>>> new_numbers = [ i+3 for i in numbers ]
>>> new_numbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

  First of all, this way of parsing lists is very, very good.

But instead of add(x), we're going to use lambda. If you're as paranoid as I am, you can:


>>> lam = lambda x:x+3
>>> n2 = []
>>> for i in numbers:
...     n2.append(lam(i))
...
>>> n2
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

  Lam is the same thing as add(x), so lambda x:x+3 completes three lines of add(x). In particular, the final return value. You can also write an example like this:


>>> g = lambda x,y:x+y  #x+y, And return the result
>>> g(3,4)
7
>>> (lambda x:x**2)(4)  # return 4 The square of
16

  Through the above example, summarize the usage method of lambda function:
  The & # 8226; Lambda is directly after the variable
  The & # 8226; The variable is followed by a colon
  The & # 8226; The colon is followed by an expression that evaluates to the return value of the function
 
In order to be concise, it is necessary to express it in a formula:


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

  A special note: while lambda functions can take any number of arguments (including optional arguments) and return the value of a single expression, lambda functions cannot contain commands and cannot contain more than one expression. Don't try to cram too much into lambda; If you need something more complicated, you should define a normal function and make it as long as you want.

As far as lambda is concerned, it doesn't give the program a performance boost, it gives the code simplicity. For example, to print a list of Numbers to the first power, second power, third power, fourth power. Lambda can be used to do this:


>>> lamb = [ lambda x:x,lambda x:x**2,lambda x:x**3,lambda x:x**4 ]
>>> for i in lamb:
...     print i(3),
...
3 9 27 81

  As a one-line function, lambda can be used in programming practice. In my experience, use as little as possible, because it probably exists more to reduce the definition of a one-line function.

The map

Let's take a look at an example, which is the first example when we talked about lambda above. Map can also be implemented:


>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      # Add each item to the list 3 >>> map(add,numbers)                #add(x) It's the function described above, but I'll just refer to the function name
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> map(lambda x: x+3,numbers)      # with lambda sure
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

  Map () is a built-in function in python. Its basic style is: map(func, seq). Func is a function and seq is a sequence object. At execution time, each element in the sequence object, in left to right order, is pulled out and stuffed into the function func, and the return value of func is stored in a list.

In the application, what map can achieve, can also be achieved in other ways. Such as:


>>> items = [1,2,3,4,5]
>>> squared = []
>>> for i in items:
...     squared.append(i**2)
...
>>> squared
[1, 4, 9, 16, 25] >>> def sqr(x): return x**2
...
>>> map(sqr,items)
[1, 4, 9, 16, 25] >>> map(lambda x: x**2,items)
[1, 4, 9, 16, 25] >>> [ x**2 for x in items ]     # This is my favorite, usually fast enough and readable
[1, 4, 9, 16, 25]

  All roads lead to Rome, the above methods, in programming, according to their own needs to choose.

On the basis of the above perceptual knowledge, the official description of map() can be viewed to make it clearer.


map(function, iterable, ...) Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

Understand the main points:
  The & # 8226; For each element in iterable, apply the function method (function) in turn (this is essentially a for loop).
  The & # 8226; Returns all the results to a list.
  The & # 8226; If there are many parameters, then function is executed in parallel for each parameter.
 
Such as:


>>> lst1 = [1,2,3,4,5]
>>> lst2 = [6,7,8,9,0]
>>> map(lambda x,y: x+y, lst1,lst2)     # Add up the corresponding items in the two lists and return a list of results
[7, 9, 11, 13, 5]

  Please note that the above example is not very difficult to write in a for loop, but if you want to extend it, please be careful to rewrite the following example in a for:


>>> lst1 = [1,2,3,4,5]
>>> lst2 = [6,7,8,9,0]
>>> lst3 = [7,8,9,2,1]
>>> map(lambda x,y,z: x+y+z, lst1,lst2,lst3)
[14, 17, 20, 15, 6]

  This shows the simplicity and elegance of map.

Preview: reduce and filter in the next lecture


Related articles: