I want to learn Python with my colleagues. I want to talk about small functions (1). I want to learn python.

Source: Internet
Author: User

I want to learn Python with my colleagues. I want to talk about small functions (1). I want to learn python.

At the beginning, we will mention a major topic: programming paradigm. What is a programming model? Reference Wikipedia:
Copy codeThe Code is as follows:
Programming paradigm or Programming paradigm (English: Programming paradigm), (paradigm is exemplary, paradigm is model, method), is a kind of typical Programming style, it refers to a typical style engaged in software engineering (can be compared with the methodology ). For example, functional programming, program programming, object-oriented programming, and Directive programming are different programming models.

The programming paradigm provides (and determines at the same time) the programmer's views on program execution. For example, in Object-Oriented Programming, Programmers think that a program is a series of interactive objects, while in functional programming, a program is considered as a stateless function compute serial.
 
Just as different groups in software engineering advocate different "Methodologies", different programming languages also advocate different "programming patterns ". Some languages are specially designed for a specific paradigm (for example, Smalltalk and Java support object-oriented programming, while Haskell and Scheme support functional programming ), there are also other languages that support multiple types (such as Ruby, Common Lisp, Python, and Oz ).
 
The relationship between the programming paradigm and the programming language may be very complex, because one programming language can support multiple paradigms. For example, C ++ supports procedural programming, object-oriented programming, and generic programming. However, designers and programmers should consider how to use these model elements to build a program. One person can use C ++ to write a fully procedural Program, and another person can also use C ++ to write a purely object-oriented program, some people may even write programs that mix up two types of paradigm.

Whether you are a beginner or an old slogan, you are advised to read the above paragraph carefully. Whether you understand it or not, you will always feel a little bit.

Here we recommend an article from the Internet: main programming paradigm

I have made a lot of programming examples. What do I want to talk about today? Today we will introduce several small functions in python. These functions are used for reference in functional programming. They are:

Filter, map, reduce, lambda, yield

With them, the biggest advantage is that the program is more concise; without them, the program can also be implemented in other ways, but it is only a bit of trouble. So, use it if it can be used.

Lambda

Lambda functions are a function that can solve the problem with only one row. It sounds so attractive. See the following example:
Copy codeThe Code is as follows:
>>> Def add (x): # define a function, increase the input variable by 3, and return the added value.
... X + = 3
... Return x
...
>>> Numbers = range (10)
>>> Numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # There is a list where you want to add 3 to each number, then output to a new list.

>>> New_numbers = []
>>> For I in numbers:
... New_numbers.append (add (I) # Call the add () function and append it to the list.
...
>>> New_numbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

In this example, add () is only an intermediate operation. Of course, the above example can be fully implemented in other ways. For example:
Copy codeThe Code is as follows:
>>> New_numbers = [I + 3 for I in numbers]
>>> New_numbers
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

First of all, this list resolution method is very good.

However, we should replace add (x) with the lambda function. If you look at the official website as paranoid as me, you can:
Copy codeThe Code is as follows:
>>> 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]

The lam here is equivalent to add (x). Please check the official correspondence. This line of lambda x: x + 3 completes the three rows (or two rows?) of add (x ?), In particular, the final return value. You can also write an example like this:
Copy codeThe Code is as follows:
>>> G = lambda x, y: x + y # x + y, and return the result.
>>> G (3, 4)
7
>>> (Lambda x: x ** 2) (4) # returns the square of 4.
16

Through the example above, we will summarize the usage of lambda functions:
• Directly follow the variables behind lambda
• The variable is followed by a colon
• The colon is followed by an expression, and the result calculated by the expression is the return value of the function.
 
To be concise and concise, it is necessary to use a sub-expression:
Copy codeThe Code is as follows:
Lambda arg1, arg2,... argN: expression using arguments

Please note: Although lambda functions can receive any number of parameters (including optional parameters) and return the value of a single expression, lambda functions cannot contain commands and cannot contain more than one expression. Do not try to add too many things to lambda functions; if you need something more complex, define a common function and then try to make it take long.

As far as lambda is concerned, it does not improve the performance of the program, but it brings about concise code. For example, to print a list, which is the first power, Second, Third Power, and fourth power of a number. Lambda can do this:
Copy codeThe Code is as follows:
>>> 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

Lambda can be used as a single-row function in programming practice. Based on my experience, try to use it as little as possible, because it may exist more to reduce the definition of a single function.

Map

Let's take a look at an example first, or the first example described above, which can also be implemented using map:
Copy codeThe Code is as follows:
>>> Numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Add 3 to each item in the list

>>> Map (add, numbers) # add (x) is the function described above, but only the function name is referenced here.
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

>>> Map (lambda x: x + 3, numbers) # Use lambda.
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Map () is a built-in function of python. Its basic style is map (func, seq), func is a function, and seq is a sequence object. During execution, each element in the sequence object is extracted from left to right and inserted into the func function, and save the return values of func to a list in sequence.

In applications, map can be implemented in other ways. For example:
Copy codeThe Code is as follows:
>>> 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] # I like it most. It is usually fast enough and readable.
[1, 4, 9, 16, 25]

All the above methods can be used in Rome as needed.

Based on the above perceptual knowledge, I will be able to better understand the official descriptions of map.

Copy codeThe Code is as follows:
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 between 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.

Key points:
• Apply function Methods (functions) to each element of iterable in sequence (this is essentially a for loop ).
• Returns a list of all results.
• If there are many parameters, the function is executed for them in parallel.
 
For example:
Copy codeThe Code is as follows:
>>> Lst1 = [1, 2, 3, 4, 5]
>>> Lst2 = [6, 7, 8, 9, 0]
>>> Map (lambda x, y: x + y, lst1, lst2) # Add the corresponding items in the two lists and return a result list.
[7, 9, 11, 13, 5]

Please note that it is not very difficult to use the for loop to write the above example. If you want to extend it, you should be careful when using for to rewrite the example below:
Copy codeThe Code is as follows:
>>> 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 that map is concise and elegant.

Notice: Next I will explain how to reduce and filter


Different python Functions

There are some differences between python3.1 and python2.x.
Most importantly, what you found
Print () function
Input () function, equivalent to raw_input () in python2.x ()
In addition, the range () function is equivalent to the xrange () function in python2.x ()
Actually, there are no many differences.
However, if you are new to python3, you are advised to read the python 3 tutorial.

A small function in python

Generally, our common website suffix (suffix) is cn, net, or com. You are talking about the domain name suffix list.
The code below is to use dot to separate domain names,
For example, www.baidu.com is split into ['www ', 'baidu', 'com']
After the for loop, go to the if branch when you get to com, and then go to the else branch. So we can see that the sdomain changes as follows:
In case of www, The sdomain contains ['www ']
When the baidu sdomain is replaced with ['baidu']
In case of com, go to the if branch, append, and change to ['baidu', 'com']
Then the join operation becomes baidu.com.

But I don't know why. If I do, I use a regular expression, or I just keep the last two parts.
Domain = url. split ('.')
If domain [-1] in suffixs:
Return string. join (domain [-2:], '.')
Else:
Return None # not valid domain

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.