Python Function Advancement (11)

Functional Advancement

Function parameter type

Invariant type parameters: integers, strings, tuples
Variable parameters: list, dictionary
1. Transfer of immutable parameters will not affect the parameters themselves.
2. Transferring variable parameters will affect the parameters themselves.

The difference between self-adding of immutable data type and variable data type

1. Judging the values of gl_num and gl_list

# The difference between self-adding of immutable data type and variable data type
# 1. judge gl_num and gl_list Value
def demo(num, num_list):
    num += num

    # List variable usage + No addition and reassignment!
    # num_list = num_list + num_list
    # Essentially, it's calling the extend ed method of the list
    
    num_list += num_list
    # num_list.extend(num_list)
    print(num)#18
    print(num_list)#[1, 2, 3, 1, 2, 3]
    print("Function completion")
gl_num = 9
gl_list = [1, 2, 3]
demo(gl_num, gl_list)
print(gl_num)# 9   Because this is a digital type, passing an immutable parameter does not affect the parameter itself.
print(gl_list)#[1, 2, 3, 1, 2, 3]   This is a variable parameter

def hanshu(a=[]):
    a.append(10)
    print(a)
hanshu()#[10]
hanshu()#[10, 10]

def hanshu(a=[]):
    a.append(10)
    print(a)
hanshu()#[10]
b=[9]
hanshu(b)#[9,10]
hanshu()#[10,10]

Namespace

Three kinds: local namespace, global namespace and built-in namespace
Local space: locals() function access
Global space: globals() function access
Built-in namespaces: Place built-in functions and exceptions.

a=3
b=4
def hanshu(x):
    c=5  #x=6
    d=6
    print("aaaa:",locals())
print("globals:",globals()["__file__"])
hanshu(6)

Operation results:

Scope

#Scope
a=3
b=30
c=300
def hsw():
    a=4
    b=40
    def hsn():
        a=5
        print(a)#L LOCAL(Local Scope: Function Internal) Prefer Local  #5
        print(b)#E Enclosing(Nested scope: Nested function's outer function's inner) Nested scope is not found locally#40
        print(c)#G GLOBAL Global scope: module Global #300
        print(__name__,min,max,id)#B Built-in Looking for built-in scopes
    hsn()
hsw()
"""
//Operation results:
5
40
300
__main__ <built-in function min> <built-in function max> <built-in function id>
"""

Global and local variables

Local variables: Defined in a function, only in effect within the function.

Global Variables: Variables defined externally from the beginning of the definition to the end of the program.

Global variables are immutable data types, and functions cannot modify the values of global variables.

Global variables are variable data types, and functions can modify the values of global variables.

global and nonlocal keywords

1.global can turn a local variable into a global variable
Format: global variable name

def hanshu():
    global a
    a += 10
    print("Inside the function:", a)


a = 20
hanshu()  # 30
print("External function", a)  # 30

2.nonlocal keywords can modify the outer layer (non-global variables)

a = 1000


def hsw():
    a = 9

    def hsn():  # Function nesting enclosing
        nonlocal a
        a = 98
        print("I'm inside.", a)  # 98

    hsn()
    print("I am external", a)  # 98


hsw()
print(a)  # 1000

Built-in function

1.abs() function

Function: Find the Absolute Value of Numbers

2.max() Function (Iterable Content, Function)

max(iterable,key,default) to find the maximum of iterator
iterable is an iterator, max traverses the iterator once for i in.. then passes each return value of the iterator as a parameter to func in key=func (commonly defined by lambda expression), and passes the execution result of func to key, and then judges the size based on key.

def hanshu(x):
    print("Haha")
    return abs(x)

a=[-1,-3,-2,-5,-4]
b=max(a,key=hanshu)
print(b)
"""
Operation results:
Ha-ha
 Ha-ha
 Ha-ha
 Ha-ha
 Ha-ha
-5
"""
#1.according to name Value comparison
a=[{"name":"a","age":20},{"name":"b","age":25},{"name":"c","age":15}]
def getName(x):
    return x["name"]
b=max(a,key=getName)
print(b)
#2.according to age Value comparison
a=[{"name":"a","age":20},{"name":"b","age":25},{"name":"c","age":15}]
def getAge(x):
    return x["age"]
b=max(a,key=getAge)
print(b)
#Sort the list of a with absolute value ascending
a=[-1,-3,-2,-5,-4]
a.sort(key=abs)
print(a)#[-1, -2, -3, -4, -5]

3.map() function

There are two parameters (function, iterative content)
Functions are computed on each element of the iteratable content in turn, and then a new iteratable content is returned.

#Calculate the square of each number in the list
def pingfang(x):
    return x * x


a = [1, 2, 3]
ret = map(pingfang, a)
for i in ret:
    print(i)


def hanshu(x):
    return x * x


a = [1, 2, 3]
b = map(hanshu, a)  # Mapping, processed values
print(b)  # <map object at 0x00000000025A7550>
c = list(b)
print(c)  # [1, 4, 9]

4.filter() function

Two parameters (function, sequence)
Used to filter sequences, filter out unqualified elements, and return a new list of qualified elements.
Two parameters (function, sequence), each element of the sequence is passed as a parameter to the function judgement, and then returned to True or False. Finally, the elements returned to True are put in the new list.

def gl(a):
    if a % 3 == 0 or a % 7 == 0:
        return True
    else:
        return False


a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = filter(gl, a)  # filter
print(b)
print(list(b))

5.zip() function

The zip function takes any number of iteratable objects as parameters and packages the corresponding elements into a tuple.
Then it returns an iterative zip object that lists its elements in a circular manner.
If the lengths of multiple iteratable objects are different, the length returned is the same as the length returned.

a=[1,2,3,4]
b=['a','b','c']
c=zip(a,b)
for x in c:
    print(x)
"""
(1, 'a')
(2, 'b')
(3, 'c')
"""

a=[1,2,3]
b=['a','b','c']
def hs(x):
    return {x[0]:x[1]}
x=map(hs,zip(a,b))
d=list(x)
print(d)
"""
//Operation results:
[{1: 'a'}, {2: 'b'}, {3: 'c'}]
"""

acquire a better understanding

a=(('a',),('b'))#When a sign is added to one of them, it becomes a tuple.
print(type(a[0]))#<class 'tuple'>
b=(('c'),('d'))#Here are two elements in a tuple, not two tuples.
x=zip(a,b)
print(x)#<zip object at 0x00000000025C6608>
for i in x:
    print(i)
"""
//The results here:
(('a',), 'c')
('b', 'd')
"""
print(list(x))#[] This is empty, because the iterator x useforIt's empty, so I'll do it again. list Time is up.

The two tuples (`a', (`b'), (`c', (`d') are generated in the format [{`a': `c'}, {`b': `d'}].

a=(('a'),('b'))
b=(('c'),('d'))
def hanshu(a):
    return {a[0]:a[1]}
x=map(hanshu,zip(a,b))
print(list(x))
"""
//Operation results:
[{'a': 'c'}, {'b': 'd'}]
"""

Anonymous function lambda

Grammar:
Variable name = lambda parameter: expression (block)

func = lambda: 3 < 2
ret = func()
print(ret)  # false

hs = lambda x, y, z: x + y + z  # Small Function Keyword
b = hs(2, 3, 4)
print(b)  # 9

x = lambda a, b: a if a > b else b
y = x(2, 3)
print(y)  # 3
a = [{"name": "War three", 'age': 19}, {"name": "lisi", 'age': 29}, {"name": "wanh", 'age': 9}]
# def getAge(x):
#     return x["age"]
x = lambda z: z['age']
b = max(a, key=x)
print(b)#{'name': 'lisi', 'age': 29}

a = [{"name": "War three", 'age': 19}, {"name": "lisi", 'age': 29}, {"name": "wanh", 'age': 9}]
b = max(a, key=lambda z: z['age'])
print(b)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = filter(lambda x: True if x % 2 == 0 else False, a)
print(list(b))  # [2, 4, 6, 8]

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(filter(lambda x: not x % 2, a)))  # [2, 4, 6, 8]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(filter(lambda x: True if x % 3 == 0 or x % 7 == 0 else False, a)))  # [3, 6, 7, 9]

a = [1, 2, 3]
b = ['a', 'b', 'c']
print(list(map(lambda x: {x[0]: x[1]}, zip(a, b))))  # [{1: 'a'}, {2: 'b'}, {3: 'c'}]

Nested scopes

def hs():  # Function execution process:

    x = 3

    def nb(n):
        return x ** n

    return nb  # Here is the return value, so b equals nb.


b = hs()  # You will encounter a return value
print(b)
print(b(2))  # That's what it is.nb(2) 9
print(b(3))  # 27


def hs():
    x = 3
    return lambda n: x ** n


b = hs()
print(b(2))  # 9
print(b(3))  # 27
def func():
    x = 2

    def nb(n, x=x):  # Can not necessarily be multiple parameters, not written in seeb(3)You'll make a mistake when it comes to time.
        return x ** n

    return nb


b = func()
print(b(3))  # 8
print(b(2, 3))  # 9


def func():
    x = 2
    return lambda n, x=x: x ** n


b = func()
print(b(3, 2))  # 8
#first
def hehe():
    a=[]
    for i in range(3):
        a.append(lambda y:y*i)
        # b=lambda y: y * i
        # a.append(b)
    return  a

z=hehe()

print(z[0](2))#4
print(z[1](2))#4
print(z[2](2))#4

#Second

def hehe():
    a=[]
    for i in range(3):

        b=lambda y,i=i: y * i
        a.append(b)
    return  a

z=hehe()

print(z[0](2))#0
print(z[1](2))#2
print(z[2](2))#4
i = 6


def x1(x=i):
    print(x)


i = 7


def x2(x=i):
    print(x)


x1()  # 6
x2()  # 7

Keywords: Lambda

Added by bahewitt on Wed, 24 Jul 2019 13:58:02 +0300