1. Variable variable scope
-
According to the different scope of variables, variables can be divided into global variables and local variables
-
Global variables: Variables that are not defined in functions or classes in Python are global variables by default.
The scope of global variables is from the beginning of the definition to the end of the program
-
Local variables: Variables defined in functions in Python are local variables.
Local variables are scoped from the beginning of the definition to the end of the function
-
Global variables are saved in the global stack area by default, and the global variables will be released automatically after the end of the program
When calling a function, the system will automatically create a temporary stack area for this function to save the data (local variables) generated in the function. The temporary stack area corresponding to the function will be released automatically when the function call ends.
-
In the function, the keyword global can be used to modify the saving method of local variables
# The global variable name is placed before the definition variable statement def func(a): global b b = 20 print(func(10)) # The variable b can be used globally print(b) # You can use the global keyword to modify the value of a global variable inside a function name = 'xiaoming' def func(a): global name #If you do not add the global keyword + variable name, another local variable value will be created. name = 'xiaohua' func(3) print(name)
2. Anonymous function lambda
-
A lambda function is also called an anonymous function, that is, the function does not have a specific name.
# function name = lambda parameter list: return value # normal function def f(x): return x**2 print f(4) # anonymous function g = lambda x : x**2 print g(4)
-
The parameter usage is the same as that of a normal function, but the formal parameter data type cannot be defined (but the type specification can be performed by defining a default value)
3. Higher-order functions with actual parameters
-
Function parameters are functions Functions are arguments Higher-order functions
-
max() min() sorted() list.sort
num_list = [1, 23, 34, 45, -4600, 52, 52, 127, 536] # Take the maximum value according to the size of the single digit print(max(num_list, key=lambda num: num % 10)) # Take the maximum value according to the absolute value print(max(num_list, key=lambda num: num **2)) # Exercise 1: Find the longest string in list1 list1 = ['Hello', 'hello', 'how are you', 'thank you! and you?', 'study hard, improve every day'] print(max(list1, key=lambda item: len(item))) # Exercise 2: Find the smallest ten-digit element in nums nums = [92, 129, 37, 99, 150, 501] print(min(nums, key=lambda item: item // 10 % 10)) # Find the largest sum of the digits in nums # method 1 print(max(nums, key=lambda item: sum([int(x) for x in str(item)]))) # Method 2 print(max(nums, key=lambda item: eval('+'.join(str(item))))) # Method 3 def sum_num(item): sum1 = 0 for x in str(item): sum1+=int(x) return sum1 print(max(nums,key=sum_num)) # Exercise 3: Sort all students according to age value from small to large students = [ {'name': 'stu1', 'age': 18, 'score': 90}, {'name': 'stu2', 'age': 22, 'score': 98}, {'name': 'stu3', 'age': 25, 'score': 78}, {'name': 'stu4', 'age': 19, 'score': 81}, {'name': 'stu5', 'age': 20, 'score': 92} ] print(sorted(students, key=lambda item: item['age']))
-
map creates a new sequence based on the elements in the original sequence, the original sequence can be one or more
map( function, sequence)
- Function requirements: There are and only (number of sequences) parameters (representing each element in the following sequence)
- There is a return value, the return value is the element in the new sequence (the return result is an iterator)
# The map( function, sequence) function has one argument # map( function, sequence1, sequence2) function has two parameters num1 = [1, 2, 3, 33, 23, 54] num2 = [1, 23, 67, 54, 345, 87] # Each element in num1 is multiplied by 10 print(list(map(lambda x:x*10,num1))) # The result is [10, 20, 30, 330, 230, 540] # Multiply the elements at the corresponding positions in num1 num2 print(list(map(lambda x,y:x*y,num1,num2))) # The result is [1, 46, 201, 1782, 7935, 4698] # Exercise 1: Get the last name of each person in names names = ['He Xiaodong', 'Zhang San', 'Li Si', 'Wang Wu', 'Wang Er', 'Zhao Liu'] print(list(map(lambda name: name[0], names))) # Exercise 2: students = [ {'name': 'stu1', 'age': 18, 'score': 90}, {'name': 'stu2', 'age': 22, 'score': 98}, {'name': 'stu3', 'age': 25, 'score': 78}, {'name': 'stu4', 'age': 19, 'score': 81}, {'name': 'stu5', 'age': 20, 'score': 92} ] subjects = ['digital information', 'Financial Mathematics', 'garden design', 'economy', 'computer software'] # ['Electronic information-stu1', 'Financial mathematics-stu2',....] print(list(map(lambda sub, stu: f'{sub}-{stu["name"]}', subjects, students)))
-
reduce combines the elements in the sequence into one data
reduce( function, sequence, initial value) combines the elements in the sequence into one data according to the rules specified by the function
- Function requirements:
- There are only two parameters (the first parameter points to the initial value, and the second parameter represents each element in the sequence
- only need a return value
- Initial value:
- Cumulative evaluation value and initial value are 0
- Cumulatively calculate the product of values, the initial value is 1
- Merge strings, the initial value is an empty string
# reduce( function, sequence, initial value) combines the elements in the sequence into one data according to the rules specified by the function result1 = reduce(lambda x, item: x + item, nums, 0) print(result1) # The result is 520 result2 = reduce(lambda x, item: x + item % 10, nums, 0) print(result2) # The result is 10 result3 = reduce(lambda x, item: (x + str(item)), nums, '') print(result3) # The result is 123014055112
- Function requirements:
4. Iterator iter
-
concept
-
The iterator is a container data type (it can be traversed or converted into a list). It cannot directly provide an iterator, and can only convert other sequences into iterators.
-
Features:
- When printing an iterator, you cannot see which elements are in the iterator.
-
Unable to get the number of elements in the iterator through len
- If you want to use the elements in the iterator, you must take the elements out of the iterator, and the taken elements will disappear forever in the iterator
-
Any data can be used as an element in an iterator
-
-
Manipulating iterators
-
create iterator
l1 = iter('abc')
-
print iterator cannot view element
print(iter('abc')) # The result is <str_iterator object at 0x7fa52ec4f760>
-
-
Manipulate the elements in the iterator
-
No matter how to get an element in the iterator, the element will disappear from the iterator
-
get a single element
next( iterator) Get the frontmost element of the iterator, and it will disappear if it is taken away
i3 = iter([1, 2, 3, 4, 5, 52, 1, 4, 1]) print(next(i3)) # 1 print(next(i3)) # 2 print(next(i3)) # 3 print(list(i3)) # [4, 5, 52, 1, 4, 1] print(next(i3)) # An error is reported because the above has become an empty iterator
-
traverse
for variable in iterator:
loop body
The iterator is empty after traversal
for x in i3: print(x)
-
-
shuffle