程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python notes 13 nonlocal and global & Generators & higher order functions

編輯:Python

One 、global and nonlocal

1.global

# global: overall situation
# 1.a Represents two different variables
a = 15 # Global scope
def check():
a = 88 # Local scope
print(a) # 88
check()
print(a) # 15
print("*" * 50)
# b.a Represents two different variables
a = 15
def check():
a = 20
a += 88 # a = a + 88
print(a) # 108
check()
print(a) # 15
print("*" * 50)
# c.a Represents the same variable
a = 15
def check():
# UnboundLocalError: local variable 'a' referenced before assignment
global a # Statement a From global variables
a += 88 # a = a + 88
print(a) # 103
check()
print(a) # 103
"""
Be careful :
1. By default , If variables in different scopes have the same name , Within the permissions that can be accessed , Visit according to the principle of proximity
2. If the variables in the global scope and the local scope have the same name , If you need to use global variables inside the function to participate in the operation , You can use the global Make a statement
"""
"""
# Interview questions
a = 15
def check():
a += 88
print(a)
check()
print(a) 103
"""

2.nonlocal

# nonlocal: Not local
# explain :nonlocal It is generally used in the nested definition of functions perhaps Closure
# 1.
def outer1():
name = "abc"
def inner1():
# UnboundLocalError: local variable 'name' referenced before assignment
nonlocal name # Statement name Not local , Is a variable within the scope of a function
name += 'hello' # name = name + 'hello'
print(name) # abchello
print(name) # abc
inner1()
print(name) # abchello
outer1()
# 2.
# a.
x = 1
def outter2():
x = 2
def inner2():
x = 3 # Define new variables
print(" Inside :",x)
print(" external :",x)
inner2()
outter2()
print(" overall situation :",x)
"""
external : 2
Inside : 3
overall situation : 1
"""
x = 1
def outter2():
x = 2
def inner2():
nonlocal x
x = 3 # Said to x = 2 Medium x Reassign
print(" Inside :",x) # 3
inner2()
print(" external :", x) # 2--》3
outter2()
print(" overall situation :",x)
"""
Inside : 3
external : 2--->3
overall situation : 1
"""
"""
Be careful :
1. By default , If variables in different scopes have the same name , Within the permissions that can be accessed , Visit according to the principle of proximity
2. In the case of nested function definitions , If the variable names in the function scope and local scope are the same ,
If you need to use variables within the scope of a function in an internal function , You can use the nonlocal Make a statement
"""
# 【 Interview questions 】 sketch global and nonlocal Use of keywords , Illustrate with examples

Two 、 generator

# 1, Concept
"""
problem :
list : Define all the elements at once , If you only need to access the first few elements , A lot of memory space will be wasted
Solution :
Use the n Elements , Only before generation n Elements , stay Python in , Use this side , The general computing mechanism is called a generator (generator)
Generators are defined in two ways :
a. Deduce the list into [] Change it to ()
b. Function combination yield, Define function generators
"""
# 1. Mode one
# List derivation
list1 = [i for i in range(10000)]
print(type(list1)) #<class 'list'>
print(list1)
# generator
ge1 = (i for i in range(10000))
print(type(ge1))
print(ge1)
# 2. Access the elements in the generator
# a.next( generator ) Get the next element in the generator
ge1 = (i for i in range(5))
# print(next(ge1))
# print(next(ge1))
# print(next(ge1))
# print(next(ge1))
# print(next(ge1))
# Be careful : Define a generator , adopt next() Get the next element in the generator , When all elements are generated and obtained , Again next(), False report StopIteration
# print(next(ge1))
# b.for loop
# for n in ge1:
# print(n)
# 3. Mode two
# a
def test1():
return 10
r1 = test1()
print(r1,type(r1)) # 10 <class 'int'>
# b
# As long as it appears inside the function yield keyword , Then the function is a function generator ,yield The data after the keyword will be the elements in the generator
def test1():
yield 10
r1 = test1()
print(r1,type(r1)) # <generator object test1 at 0x0000021523610570> <class 'generator'>
# print(next(r1))
for n in r1:
print(n)
# c.
def test2():
yield 10
yield 20
yield 30
r2 = test2()
for n in r2:
print(n)
# d.
# Get... In a generator 3 Elements
def test3(n):
for i in range(n):
yield i ** 2
r3 = test3(5)
print(next(r3)) # 0
print(next(r3)) # 1
print(next(r3)) # 4
# Get the third of the three generators respectively 0 Elements
def test3(n):
for i in range(n):
yield i ** 2
print(next(test3(5)))
print(next(test3(5)))
print(next(test3(5)))
# Be careful : In the function generator , Just call the function once , It means that a new generator is generated

3、 ... and 、 Iteratable objects and iterators

"""
【 Interview questions 】 Briefly describe the differences and relationships between iteratable objects and iterators
difference :
Iteratable object :Iterable, Can act directly on for The object of the cycle 【 have access to for Loop through the object in which the element 】,
Such as :list,tuple,dict,set,str,range(), Generator, etc
iterator :Iterator, Can act directly on for loop , Or through next() Get the object of the next element ,
Such as : generator
contact :
Iterators must be iterative objects , Iteratable objects are not necessarily iterators
however , It can be realized through system functions iter() Convert iteratable objects that are not iterators to iterators
"""
# isintance( Variable , type ): Determine whether the type of a variable is the specified type
from collections import Iterable,Iterator
# 1.
print(isinstance([34],Iterable)) # True
print(isinstance((34,),Iterable))
print(isinstance("agag",Iterable))
print(isinstance({"a":10},Iterable))
print(isinstance({457},Iterable))
print(isinstance(range(5),Iterable))
print(isinstance((i ** 2 for i in range(5)),Iterable))
print(isinstance(34,Iterable)) # False
print(isinstance(True,Iterable)) # False
# 2.
print(isinstance([34],Iterator)) # False
print(isinstance((34,),Iterator))
print(isinstance("agag",Iterator))
print(isinstance({"a":10},Iterator))
print(isinstance({457},Iterator))
print(isinstance(range(5),Iterator))
print(isinstance((i ** 2 for i in range(5)),Iterator))
print(isinstance(iter([34]),Iterator))
print(isinstance(iter((34,)),Iterator))
print(isinstance(iter("agag"),Iterator))
print(isinstance(iter({"a":10}),Iterator))
print(isinstance((i ** 2 for i in range(5)),Iterator))

Four 、 Higher order function 【 Focus on mastering 】

The nature of functions : A function is a variable , The function name is a variable name , A function can be used as a parameter or return value of another function

If A Function as B The parameters of the function ,B When the function call is complete , We'll get a result , be B Functions are called higher order functions

1.map() mapping

"""
map(func,iterable): The return value is one iterator
func: function
iterable: Iteratable object , It can be more than one , Common list
function : take iterable Each element in is passed to func,func Return a result , The result becomes an element in the iterator
"""
# 1. demand : Create a container , The element is 1,4,9,16,25
# Mode one
list1 = [i ** 2 for i in range(1,6)]
print(list1)
# Mode two
def func1(a):
# print(a)
return a ** 2
r1 = map(func1,range(1,6))
print(r1) # <map object at 0x1096201d0>
print(list(r1))
# Mode three : recommend
list3 = list(map(lambda x:x ** 2,range(1,6)))
print(list3)
# working principle :range(1,6)-----》func mapping ----》[1, 4, 9, 16, 25]
# practice : Use one line of code to achieve the specified effect : It is known that [2,7,3], Convert to ['2','7','3']
numlist = [2,7,3]
# Mode one
new_list1 = [str(num) for num in numlist]
print(new_list1)
# Mode two
new_list2 = list(map(lambda x:str(x),numlist))
print(new_list2)
# 2.
# Be careful 1: The parameters of the function are determined by the number of iteratible objects
# working principle : The element at the same index in multiple iteratible objects is automatically passed to the specified function , Do the corresponding operation
# Be careful 2: The number of elements in multiple iteratible objects can be different , Use a small number of iteratible objects as a reference
def func1(x,y,z):
return x + y + z
r21 = map(func1,[1,2,3],[4,5,6,1],[3,6,8,5])
print(list(r21))
r22 = list(map(lambda x,y,z:x + y + z,[1,2,3],[4,5,6,1],[3,6,8,5]))
print(r22)
# 3.map(func,iter) Medium func It can be a system function , It can also be a custom function

2.reduce() Reduce

"""
reduce(func,seq):
func: function
seq: Sequence
function : take seq The elements in are based on func The specified operation
working principle : First , take seq No 0 And the first 1 Elements passed to func, Do the corresponding operation , Return results 1,
next , Will result in 1 and seq No 2 Passed to func, Do the corresponding operation , Return results 2,
....
until seq All the elements in participate in the operation
eg:
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates : ((((1+2)+3)+4)+5)
"""
"""
explain :
a.map: A container is known , adopt func The mapping relation of , Get a new container
b.reduce: A container is known , adopt func The calculation of , Get a data
"""
from functools import reduce
# 1. demand : It is known that [1, 2, 3, 4, 5], Find the sum of the elements in the list
list1 = [1, 2, 3, 4, 5]
# Mode one
sum1 = sum(list1)
print(sum1)
# Mode two
def func1(x,y):
# print(x,y)
return x + y
sum2 = reduce(func1,list1)
print(sum2)
# Mode three
sum3 = reduce(lambda x,y:x + y,list1)
print(sum3)
# practice : seek 15 The factorial
r = reduce(lambda x,y:x * y,range(1,16))
print(r)
# Be careful :reduce(func,seq) in func The argument to must be two

3.filter() Filter

"""
filter(func,iterable): The return value is one iterator
func: function
iterable: Iteratable object
function : take iterable Each element in is passed in turn to func, If func return True, It means that it is necessary to keep , Otherwise, it means you need to filter out
"""
"""
explain :
a.map: A container is known , adopt func The mapping relation of , Get a new container
b.reduce: A container is known , adopt func The calculation of , Get a data
c.filter: A container is known , adopt func Whether the return value of is True, Get a new container
"""
# demand : It is known that , Filter out the odd numbers list1 = [234,5,6,7,8,51,100,56,7,8]
list1 = [234,5,6,7,8,51,100,56,7,8]
# Mode one
new_list1 = [n for n in list1 if n % 2 == 0]
print(new_list1)
# Mode two
def func1(x):
# if x % 2 == 0:
# return True
# return False
return x % 2 == 0
r1 = filter(func1,list1)
print(r1)
print(list(r1))
# Mode three
r2 = filter(lambda x:x % 2 == 0,list1)
print(list(r2))
r2 = filter(lambda x:True if x % 2 == 0 else False,list1)
print(list(r2))

4.sorted() Sort

"""
summary :
Difference :
1. Different ways of calling
list .sort(key=func,reverse=True)
sorted( list ,key=func,reverse=True)
2. The results are different
sort(): Is sorted inside the original list
sorted(): A new list is generated
The same thing :
1. The default is ascending
2. If descending order is required , You only need to set reverse=True
3. If you need to customize the collation , All need to be given key Assign a function
"""
# 1. Ascending
list1 = [34,5,24,10]
list1.sort()
print(list1)
list1 = [34,5,24,10]
l1 = sorted(list1)
print(l1)
# 2. Descending
list1 = [34,5,24,10]
list1.sort(reverse=True)
print(list1)
list1 = [34,5,24,10]
l1 = sorted(list1,reverse=True)
print(l1)
# 3. Custom collation
# a. System function
list1 = ['fafa','gatgagah','dd']
list1.sort(key=len)
print(list1)
list1 = ['fafa','gatgagah','dd']
r1 = sorted(list1,key=len)
print(r1)
# b. Custom function
# Sort the list by student grade from large to small
students = [
{'name': ' floret ', 'age': 19, 'score': 90, 'gender': ' Woman ', 'tel':
'15300022839'},
{'name': ' Mingming ', 'age': 20, 'score': 40, 'gender': ' male ', 'tel':
'15300022838'},
{'name': ' Huazai ', 'age': 18, 'score': 90, 'gender': ' Woman ', 'tel':
'15300022839'},
{'name': ' quietly ', 'age': 16, 'score': 90, 'gender': ' Unknown ', 'tel':
'15300022428'},
{'name': 'Tom', 'age': 17, 'score': 59, 'gender': ' Unknown ', 'tel':
'15300022839'},
{'name': 'Bob', 'age': 18, 'score': 90, 'gender': ' male ', 'tel':
'15300022839'}
]
students.sort(reverse=True,key=lambda subdict:subdict['score'])
print(students)
students = [
{'name': ' floret ', 'age': 19, 'score': 90, 'gender': ' Woman ', 'tel':
'15300022839'},
{'name': ' Mingming ', 'age': 20, 'score': 40, 'gender': ' male ', 'tel':
'15300022838'},
{'name': ' Huazai ', 'age': 18, 'score': 90, 'gender': ' Woman ', 'tel':
'15300022839'},
{'name': ' quietly ', 'age': 16, 'score': 90, 'gender': ' Unknown ', 'tel':
'15300022428'},
{'name': 'Tom', 'age': 17, 'score': 59, 'gender': ' Unknown ', 'tel':
'15300022839'},
{'name': 'Bob', 'age': 18, 'score': 90, 'gender': ' male ', 'tel':
'15300022839'}
]
new_students = sorted(students,reverse=True,key=lambda subdict:subdict['score'])
print(new_students)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved