Python Python scope of the road, anonymous functions, functional programming, map function, filter function, reduce function

First, the scope


return can return any value
example

Copy the code
def test1():
    print("test1")
def test():
    print("test")
    return test1
res  = test()
print(res)
Copy the code

 

  

Output

test
<function test1 at 0x021F5C90>

 

  


Analysis: Here print (res) output is test1 function address in memory, return also can return
, parentheses can run the function

Example 2

Copy the code
name = "pony"
def test1():
    name = "nicholas"
    def inner():
        name = "jack"
        print(name)
    return inner
res  = test1()
print(res)
res()
Copy the code

 

  

Output

<function test1.<locals>.inner at 0x02195C48>
jack

 

  

Analysis:
test1 function returns the memory address of the inner function, and assigned to the RES, so the last parentheses can be performed directly after RES, note that the inner function is performed here, the selected print name local variable name = "jack "rather than choose res executed and () name where =" pony "


Example 3

Copy the code
DEF foo (): 
    name = 'Jack' 
    DEF bar (): 
        name = 'Pony' 
        Print (name) 
        DEF TT (): 
            Print (name) 
        return TT 
    return bar 
R1 = foo () # returns the memory function bar address 
r2 = r1 () # perform the function bar, tt function returns the memory address 
r3 = r2 () # tt executed function, the output pony
Copy the code

 

  

Output

pony
pony

 

  

Analysis: r1 foo function is performed, the resulting memory address bar function, r2 bar function is executed, the return address of the memory function tt, tt executed function, the output pony.
Here you can also directly write
foo () () ()
foo () is r1, foo () () is r2, foo () () ( ) is r3.

 

Second, the anonymous function

 

1、lambda

example


lambda x: x + 1
X here corresponds to the function from the parameter definition, x + 1 corresponding to the return value returned
DEF Calc (X)
return. 1 + X
The custom functions and lambda x: x + 1 is equivalent to of

 

lambda functions are typically treated by direct addition and subtraction, multiplication, followed by a string
examples

def calc(x):
    return x+1
res = calc(10)
print(res)
print(calc)

 

  

Output

11
<function calc at 0x02245C48>

 

  

Example 2

 

print(lambda x:x+1)

 


Output

<function <lambda> at 0x021B5C48>

 

  

Analysis: where lambda is the function address in memory, and are calc function (without performing, that is not bracketed) the same

Call lambda ()

example

func = lambda x:x+1
res = func(10)
print(res)

 

  

Export

1
 

  


Analysis: lambda function call needs to be assigned to a variable lambda function, with the variable name () is executed with parameters executed, the parameters within the brackets Similar self-defined function argument, by invoking parameter transmitted.

 

Example 3

print(list(filter(lambda x:x if x % 2 == 0 else "" ,range(10))))

 

  Output

[2, 4, 6, 8]

 

  Analysis: lambda can be used if -else statement, but can not be used if statements must be written with a single if-else statements

 

2, lambda return multiple values


example

X = the lambda FUNC, Y, Z: X + Y + Z 
RES = FUNC (10,11, 12) 
Print (RES) 
# write or 
print (func (10,11,12))

 

  

Example 2

X = the lambda FUNC, Y, Z: (. 1 + X, + Y. 1, Z + 1'd) 
RES = FUNC (10,11, 12) 
Print (RES) 
# or write directly 
print (func (10,11,12 ))

 

  

Output

(11, 12, 13)
(11, 12, 13)

 

  

Analysis: Returns the value needed here plurality of brackets and commas


Third, the functional programming

 

1, three programming methodology

 

Process-oriented programming, functional programming, object-oriented programming

Process-oriented:
the definition of
a process-centric programming ideas. These are based on what is happening to program as the main target, unlike object-oriented who is affected.
The simplest is the task into steps one by one, step by step implementation.

 

Functional programming:
is defined
in computer science, functional programming is a programming paradigm, it is calculated is described as expressions are evaluated and avoids state and data changes. Functional programming inside the "function" refers to a mathematical function.

For any programming function, need to meet the following three conditions, it can be converted into pure mathematical function.

Each function must contain input parameters (independent variables)
of each function must have a return value (as the dependent variable)
whenever a given function is called, the return value must be consistent.

 

Object-oriented programming
is defined

Object-oriented programming --Object Oriented Programming, referred to as OOP, is a programming idea. OOP object as the basic unit of the program, an object contains function data and operational data.

Object-oriented programming and computer program as a collection of a set of objects, and each object may receive a message sent, other objects, and to process these messages, executing a computer program is a series of message passing between objects .


2, functional programming recursive call

Defined higher-order functions
(1) the function name can be passed as parameters
(2) The return value may be a parameter


example

Copy the code
def foo(n): #n=bar
    print(n)
 
def bar(name):
    print('my name is %s' %name)
foo(bar)
foo(bar("nicholas"))
Copy the code

 

  

Output

<function bar at 0x02225C48>
my name is nicholas
None

 

  


Analysis: Here foo (bar), where the bar is passed as a parameter as a function foo (), bar is a memory address. foo (bar ( "nicholas")) in, bar ( "nicholas") function is executed, the first output my name is nicholas, then perform the function foo, bar since the function has no return value, the execution foo () output None.


3, tail call optimization (optimization tail recursion)

Last call: calling a function in the final step of another function (not necessarily the last line of the last step function)

examples

def bar(n):
    return  n
def foo(x):
    return bar(x)

 

  


Here's return bar () function is the last step.

example

Copy the code
def test(x):
    if x > 1:
        return True
    elif x == 1:
        return False
    else:
        return False
test(1)
Copy the code

 

  

Analysis: The final step here is to perform elif x == 1 the following return False statement.

Tail-recursive and non-recursive tail
non-tail recursion

def cal(seq):
    if len(seq) == 1:
        return  seq[0]
    head , *tail = seq
    return  head + cal(tail)
print(cal(range(100)))

 

  

Tail recursion

Copy the code
def cal(l):
    print(l)
    if len(l) == 1:
        return  l[0]
    frist,second,*args = l
    l[0] = frist + second
    l.pop(1)
    return cal(l)
x = cal([i for i in range(10)])
print(x)
Copy the code

 

  


3, map () function


map () will do the mapping function in accordance with the specified sequence provided.

Map (function, Iterable, ...)
function - a function, there are two parameters
iterable - one or more sequences of
which has two parameters, the first parameter is a function, the second iteration to be the object.

Examples
needs, li1 = [1,3,4,5,7,10] Each element into its own square.


Solve for loop

li1 =   [1,3,4,5,7,10]
li = []
for i in li1:
    li.append(i ** 2)
res = li
print(res)

 

  

Upgrade requirements, handle multiple lists, each element of the list into their own square.

Copy the code
li1 =   [1,3,4,5,7,10]
def map_test():
    li = []
    for i in li1:
        li.append(i ** 2)
    return li
res = map_test(li1)
print(res)
Copy the code

 

  

Demand continues to escalate, the square of each element of the original list, the composition of the new list

 

Copy the code
li1 =   [1,3,4,5,7,10]
def pow_test(n):
    return n ** 2
def map_test(fun,array):
    li = []
    for i in array:
        res = fun(i)
        li.append(res)
    return li
res1 = map_test(pow_test,li1)
print(res1)
Copy the code

 

  

Analysis: Parameters fun here map_test function is passed a function, that function is this map_test higher-order functions, call other functions in map_test function, the object passed to the second processing. Here two map_test (), pow_test () is implemented together function map () function returns.


Here () function map treated with

 

li1 = [1,3,4,5,7,10]
res1 = list(map(lambda x:x**2,li1))
print(res1)

 

  

Analysis: map () function of the first parameter is a function, i.e., anonymous function, there is no need parentheses performed only representative of a parameter of the treatment, Map () The second parameter is an iterative object to be processed.
map () function is a direct result of a process map () function of the memory address, it is an iterative type, and needs list into a list.

Here map () function's first argument is not necessarily to write lambda functions, you can also write a custom function name.


example

 

def reduce_one(n):
    return n - 1
li1 =   [1,3,4,5,7,10]
res1 = list(map(reduce_one,li1))
print(res1)

 

  

Output

[0, 2, 3, 4, 6, 9]

 

  



About map () function output processing results

Examples of
the processing result for loop

li1 =   [1,3,4,5,7,10]
res1 = map(lambda x:x**2,li1)
for i in res1:
    print(i)
print(res1)

 

  

Output

Copy the code
1
9
16
25
49
100
<map object at 0x02185790>
Copy the code

 

  

Map function directly

= in Li1 [1,3,4,5,7,10] 
RES = List (Map (the lambda X: X ** 2, in Li1)) 
Print ( "Map processing result", res)

 

  

Output

 

map processing result is [1, 9, 16, 25, 49, 100]

 

  

Analysis: The results can be seen here map () function is a direct output of the iterative object list can be coupled into a list.


4, filter () function


filter () function is a built-in Python Another useful higher order function, filter () function accepts a function f and a list, the role of this function f is determined for each element, returns True or False, filter () The Analyzing results filtered out automatically ineligible element, and returns the new list of qualified elements.
filter: filter, to filter out

Example
, from a list [1, 4, 6, 7, 9, 12, 17] to remove an even number, odd reserved

With defined functions and solve for loop

Copy the code
li = [1, 4, 6, 7, 9, 12, 17]
li1 = []
def filter_old(n):
    if n % 2 == 1:
        li1.append(n)
def test():
    for i in li:
        res = filter_old(i)
test()
print(li1)
Copy the code

 

  

Export

[1, 7, 9, 17]

 

  

Here you can also address directly with the filter function.

li = [1, 4, 6, 7, 9, 12, 17]
def filter_old(n):
    if n % 2 == 1:
        return n
res = list(filter(filter_old,li))
print(res)

 

  


Output

[1, 7, 9, 17]

 

  

Or, more streamlined some of

 

it = [1, 4, 6, 7, 9, 12, 17] 
nothing = list (filter (lambda n: n% 2 == 1, I)) 
print (anything)

 

  

Output

[1, 7, 9, 17]

 

  

Analysis: where lambda processing logic function is a function, ultimately returned to the n n% 2 == 1 meet the condition
where the map function as List need to convert it to the list.

example

it = [1, 4, 6, 7, 9, 12, 17] 
nothing = list (filter (lambda n: not n% 2 == 1, I)) 
print (anything)

 

  

Analysis: lambda here you can also add not.

example

Copy the code
li = [
    {"name":"jack","age":53},
    {"name":"pony","age":46},
    {"name":"charles","age":53},
    {"name":"richard","age":44}
 
]
v = list(filter(lambda p:p["age"]<45,li))
print(v)
Copy the code

 

  

Output

[{'name': 'richard', 'age': 44}]

 

  

Analysis: Here lambda is the return of qualified elements p, through each element in the sequence determines each element of the Boolean value is True if you stay.


5, reduce () function


reduce () can be directly used in python2
in python3 need to add modules to import
from functools import reduce

reduce () method using the form reduce (f (x), Itera). Yes, and as its form map () function. However, the parameter f (x) must have two parameters. reduce () function that is called: the results and continues to the next element in the sequence is calculated as the accumulator.

Examples
demand list [1,2,3,4,5,6] all the elements together.
Solve for loop

li = [1,2,3,4,5,6] 
I = 0 
for i in li: 
    I = I + I 
print (I)

 

  

2 requirements, list of requirements li = [1,2,3,4,5,6] is multiplied by each element of the final result

Treated with a custom function

Copy the code
= Li [1,2,3,4,5,6] 
DEF Test (X, Y): 
    return X * Y 
DEF test1 (FUNC, Array): 
    RES = Array.pop (0) 
    # indicates where a first list elements 
    #pop () delete a value, and may obtain the current value of the deleted 
    for I in Array: 
        res = FUNC (res, I) 
        # this is the result of the multiplication of the incoming and next element, the initial value res = array [0]. 
    RES return 
V = test1 (Test, Li) 
Print (V)
Copy the code

 

  

Output

720

 

Analysis: Here two custom function calls another function processed by the function. Herein may be used directly reduce () function processing.

rom functools import reduce
li = [1,2,3,4,5,6]
v = reduce(lambda x,y:x*y,li)
print(v)

 

  

Export

720

 

  

Analysis: Note that this method is no longer used list.

There are three parameters reduce
function of function with two arguments, parameters required
sequence tuple, list, dictionary, string, etc. iterables, required parameter
initial value of the initial, optional parameters

If no initial value init, the second direct execution parameter iterables treated by the first parameter func.
If the initial value Init, the first initial value for the first element and a second parameter to be passed is processed by func, and then after the integrated value by integrating the second element.

example

from functools import reduce
li = [1,2,3,10]
v = reduce(lambda x,y:x*y,li,10)
print(v)

 

  


Output

 

600

 

  


Analysis: First, an initial value 10 10 * 1 obtained here, then obtain a cumulative value of 10 20 * 2, * 3 and 20, and so on, and finally to give 600.

 

6, map (), filter (), reduce () Summary

map ()
processing each element of the sequence, the result is a 'list' (memory address), the 'list' and the number of elements in the same position as the original

filter ()
filter through each element of the sequence, each element of the Boolean value is determined, if the stay is True

reduce()

A processing sequence, then the merge operation sequence

Guess you like

Origin www.cnblogs.com/QaStudy/p/11514920.html