Python path [Part 3]: Python BASICS (part 3) and python 3

Source: Internet
Author: User

Python path [Part 3]: Python BASICS (part 3) and python 3

INSTRUCTOR: http://www.cnblogs.com/wupeiqi

Lambda expressions

When learning conditional operations, a simple if else statement can be represented by a Trielement operation, namely:

# Normal condition statement if 1 = 1: name = 'luotianshuai' else: name = 'shuague' # name = 'luotianshuai' if 1 = 1 else 'shuague' # This is short for if else. # When the if condition is set, when the name is 'luotianshuai', it is: 'shuaige ', syntactic sugar!

 

Is there a short name for the function? There are also some lambda expressions!

Lambda and if else perform the same Trielement operation to simplify functions. However:

1. Only simple operations can be performed.
2. Automatic return

Let's take a look at the comparison of the following two functions:

'''Normal function''' def func (arg): return arg + 1 result = func (100) print result '''lambda expression''' func2 = lambda: a + 1 result = func2 (10000) # When calling a function, the equal sign on the left of the lambda expression is called by the function! Print result # execution result: #101 #10001
Built-in function 2

1. map

Traverse the sequence, operate on each element in the sequence, and finally obtain the new sequence.

Explanation:

In Python, the most basic data structure is sequence ). Each element in the sequence is assigned a sequence number, that is, the position of the element, also known as the index. The first index is 0, the second index is 1, and so on. The last element in the sequence is marked as-1, the second last element is-2, and so on.

Python contains 6 built-in sequences, including lists, tuples, strings, Unicode strings, buffer objects, and xrange objects.

'''Example 1 ''' li = [11,22, 33] def func1 (arg): return arg + 1 # Here we can multiply the division by new_list = map (func1, li) # Here, map calls the function, and you can specify the function rules by yourself. You can define the function as what it will do! Print new_list output result: [12, 23, 34] ''' Example 2 ''' li = ['shuague', 'nihao',] def func1 (arg ): return '% s test string' % arg # Or use + to concatenate all the evil ones. + you don't have to use it. He will open up new space in the memory! New_strlist = map (func1, li) print new_strlist output result: ['shuaige test string ', 'nihao test string'] ''' Example 3 ''' li = 'abcdefg' def func1 (arg): return '% s test string' % argnew_list = map (func1, li) print new_list # result: ['a test string', 'B test string', 'c test string', 'd test string', 'e test string ', 'F test string', 'G test string']Map example

 

Use lambda expressions:

Li = [100, 111,122,133,144,155, 44, 55] new_li = map (lambda a: a +, li) print new_li # output result: [] # multiple list operations: l1 = [, 44, 55] l2 = [, 66] l3 = [, 77] print map (lambda a1, a2, a3: a1 + a2 + a3, l1, l2, l3) # output result: [66, 99,132,165,198] # note that the elements in the map function list must be the same! Otherwise, the following error will be reported! # TypeError: unsupported operand type (s) for +: 'int' and 'nonetype '. If you want to see l1 = [, 22, 55] l2 =, 66] l3 = [,] # One less l3 data. If the element is empty, this element is None when it is called.Lambda expressions

 

Ii. filter

Filter the elements in the sequence to obtain the sequence that meets the condition!

Li = [11,22, 33,44, 55,66, 77,88] print filter (lambda a: a> 33, li) output result: [44, 55, 66, 77, 88]

Iii. reduce

Perform accumulative operations on all elements in the sequence

Li = [1, 2, 3, 4, 5, 6, 7, 8] result = reduce (lambda a1, a2: a1 + a2, li) # The first parameter of multiplication, division, addition, and subtraction print result # reduce. The function must have two parameters, because it is the second parameter of the Operation # reduce, sequence to be cyclic # third parameter of reduce, initial value # Initial Value li = [1, 2, 3, 4, 5, 6, 7, 8] result = reduce (lambda a1, a2: a1 + a2, li, 100000) # multiplication, division, addition, and subtraction print result

Default parameters:

Yield Generator

Differences between yield and return:

After yield jumps out of the function, it records the status of the current function. When it is called next time, it starts from the recorded status!

Return will jump out of the function!

1. Compare the difference between range and xrange

>>> print range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> print xrange(10)xrange(10)

As shown in the code above, range creates all the specified numbers in the memory, and xrange does not create immediately. Each array is created only during iteration cycles.

See the following example: (custom generator)

def mrange(arg):    seed = 0    while True:        seed = seed +1        if seed > arg:            return        else:            yield seedfor i in mrange(10):    print i
Bubble Algorithm

 

Requirement: sort the list [13, 22, 6, 99, 11] from small to large.

 

Idea: compare two adjacent values, place the larger values on the right, and compare them in sequence!

Bubble algorithm schematic:

Bubble algorithm example:
There are five elements in the list to compare and then use the median to replace them cyclically!
In this case, we can use a loop to perform the previous loop and use an expression to construct an internal loop!

li = [13,22,6,99,11]for n in range(1,len(li)):    for m in range(len(li)-n):        num1 = li[m]        num2 = li[m+1]    if num1 > num2:        temp = li[m]        li[m] = num2        li[m+1] = tempprint li

The principle is the same as the following:

Li = [13, 22, 6, 99, 11] for m in range (4): # equivalent to: for m in range (len (li)-1) num1 = li [m] num2 = li [m + 1] if num1> num2: temp = li [m] li [m] = num2 li [m + 1] = tempprint lifor m in range (3): # equivalent: for m in range (len (li)-2) num1 = li [m] num2 = li [m + 1] if num1> num2: temp = li [m] li [m] = num2 li [m + 1] = tempprint lifor m in range (2): # is equivalent: for m in range (len (li)-3) num1 = li [m] num2 = li [m + 1] if num1> num2: temp = li [m] li [m] = num2 li [m + 1] = tempprint lifor m in range (1): # equivalent: for m in range (len (li)-4) num1 = li [m] num2 = li [m + 1] if num1> num2: temp = li [m] li [m] = num2 li [m + 1] = tempprint liBubble algorithm principle decorator

The decorator is a function, but it can have special meanings. It is used to decorate functions or classes. You can add operations before and after the function is executed.

Simply put, you can wrap the original function without modifying the original function!

 

1. Start-ups have N business departments and 1 Basic Platform department. The basic platform is responsible for providing underlying functions, such as database operations, redis calls, and monitoring APIs. When using basic functions, the business department only needs to call the functions provided by the basic platform. As follows:

 

############## Basic platform Functions: ################# def f1 (): print 'f1' def f2 (): print 'F2' def f3 (): print 'F3' def f4 (): print 'F4' ############## functions provided by business department A to call the basic platform ############ ### f1 () f2 () f3 () f4 () ############## functions provided by the basic platform are called by business department B ############## f1 () f2 () f3 () f4 ()

At present, the company is proceeding in an orderly manner. However, in the past, developers on the basic platform did not pay attention to verification issues when writing code, that is, the functions provided by the basic platform can be used by anyone. Now all functions of the basic platform need to be reconstructed to add verification mechanisms for all functions provided by the platform, that is, verification is performed before the function is executed.

The boss handed over his work to Low B. He did this:

 

Negotiate with each business department, write code for each business department, and verify the code before calling the basic platform functions. This way, the basic platform does not need to be modified.

 

On that day, Low B was fired...

The boss handed over his work to Low BB. He did this:

Only refactor the code of the basic platform, so that N business department does not need to make any modifications
############## Basic platform Functions: ################# def f1 (): # verify 1 # verify 2 # verify 3 print 'f1' def f2 (): # verify 1 # verify 2 # verify 3 print 'F2' def f3 (): # verify 1 # verify 2 # verify 3 print 'F3' def f4 (): # verification 1 # verification 2 # verification 3 print 'f1' ################ business department unchanged ######### ######### functions provided by the basic platform are called by business department A ### f1 () f2 () f3 () f4 () ### functions provided by business department B to call the basic platform ### f1 () f2 () f3 () f4 ()Modify the code of the original basic platform

After a week, Low BB was fired...

The boss handed over his work to Low BBB. He did this:

Only code on the basic platform is restructured, and no modifications are required for other business departments.
############## Basic platform Functions ################## def check_login (): # verify 1 # verify 2 # verify 3 passdef f1 (): check_login () print 'f1' def f2 (): check_login () print 'F2' def f3 (): check_login () print 'F3' def f4 (): check_login () print 'F4'Create a new function and apply the function to the original basic function.

The boss looked at the implementation of Low BBB, and smiled with a sigh of relief. He chatted with Low BBB for a day:

The boss said:

Code writing follows the closed development principle. Although this principle is intended for object-oriented development, it is also applicable to functional programming. In simple terms, it specifies that the implemented Function Code cannot be modified, but can be extended, namely:

  • Closed: Implemented functional code blocks
  • Open: extended development

If the open and closed principle is applied to the above requirements, the Code cannot be modified within the f1, f2, f3, and f4 functions. The boss gave the Low BBB an implementation solution:

Def w1 (func): def inner (): # verify 1 # verify 2 # verify 3 return func () return inner @ w1def f1 (): print 'f1' @ w1def f2 (): print 'F2' @ w1def f3 (): print 'F3' @ w1def f4 (): print 'F4'

 

The above code is only modified on the basic platform, so that the [verification] operation can be performed before other people call the f1 f2 f3 f4 function, other business departments do not need to perform any operations.

Low BBB was so scared that he asked, What is the internal execution principle of this code?

The boss was about to get angry. Suddenly the mobile phone of Low BBB fell to the ground, and the screen saver was just a picture of his girlfriend of Low BBB. The old freshman looked tight and shook his face. He made a friend of Low BBB. The following is a detailed description:

Take f1 as an example:

def w1(func):    def inner():        print 'gongneng1'        func()        print 'gongneng2'    return inner@w1def f1():    print 'f1'f1()

During execution, python is executed from top to bottom. First, it is executed to def w1 (func): Here, def w1 (func) is loaded to the memory.

When @ w1 is executed, @ w1 is the python syntax sugar! He will encapsulate the functions below.

Pass the f1 function as the def w1 (func) parameter! That is, f1 () = w1 (f1)

Then def w1 (func): = w1 (f1) will execute:

Def inner (): print 'gongneng1 'func () # func () = f1 () "original function" print 'gongneng2' return inner # Then output the encapsulated function to the original function

@ W1 is equivalent to a replacement.

Def f1 () <=> def inner ()

@w1def f1():         #  ==def inner() :    print 'f1'    #           print 'gongneng1'                  #           func()                  #           print 'gongneng2'

 

2. What if the decorated function has parameters?

Def w1 (func): def inner (arg): # verify 1 # verify 2 # verify 3 return func (arg) return inner @ w1def f1 (arg ): print 'f1' a parameter ################################# def w1 (func): def inner (arg1, arg2): # verify 1 # verify 2 # verify 3 return func (arg1, arg2) return inner @ w1def f1 (arg1, arg2 ): print 'f1' two parameters ################################# def w1 (func): def inner (arg1, arg2, arg3): # verify 1 # verify 2 # verify 3 return func (arg1, arg2, arg3) return inner @ w1def f1 (arg1, arg2, arg3): Three print 'f1' Parameters

Use Dynamic Parameters!

Def w1 (func): def inner (* args, ** kwargs): # verify 1 # verify 2 # verify 3 return func (* args, ** kwargs) return inner @ w1def f1 (arg1, arg2, arg3): print 'f1'

3. Can a function be decorated by multiple decorators?

def w1(func):    def inner(*args,**kwargs):        print 'gongneng1'        func(*args,**kwargs)        print 'gongneng2'    return innerdef w2(func):    def inner(*args,**kwargs):        print 'gongneng3'        func(*args,**kwargs)        print 'gongneng4'    return inner@w1@w2def f1(arg,arg2,arg3):    print arg,arg2,arg3f1('nihao','tianshuai','shuaige')

Output result:

gongneng1gongneng3nihao tianshuai shuaigegongneng4gongneng2

This is decorated by multiple decorators. In fact, it is a layer of decoration! Do not wrap yourself in!

4. Are there any more hanging decorations?

Def Filter (a1, a2): def outer (main_func): def wrapper (request, kargs): print a1 main_result = main_func (request, kargs) print a2 return main_result return wrapper return outer @ Filter (f5, f6) def Index (request, kargs): print 'index''' 1. Step 1: load def Filter (a1, a2) to memory 2. Step 2: @ Filter (f5, f6) = the decorator ==@ outer is called and then returned to function 3. Step 3: Execute the outer function and return it to the index function Index = wrapper4. Execute the wrapper function, in addition to the parameters given by the original function, the modifier can also call its own defined parameter '''

In addition to the parameters given by the original function, the decorator can also call its own defined parameters.

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.