Function 3
1, Advanced usage of map
map Create a new sequence by specifying rules for the elements in one or more sequences map(function,sequence) -----Converts elements in a sequence into elements in a new sequence by specifying rules Function requirements: there is only one parameter -----Points to each element in the subsequent sequence There is a return value -----Elements in the new sequence (use parameters to represent the elements in the original sequence and describe the relationship between the new sequence elements and the original sequence elements) map(function,Sequence 1,Sequence 2) -----Convert the elements in two sequences into elements in a new sequence through the rules specified by the function Function requirements: there are only two parameters -----Point to the elements in the next two sequences respectively There is a return value -----Elements in the new sequence (use parameters to represent the elements in the original sequence and describe the relationship between the new sequence elements and the original sequence elements) When there are multiple sequences, the processing is the same as that of two sequences
eg:
nums = [84, 72, 67, 90, 31] # Get number of digits # Derivation new_nums = [i % 10 for i in nums] print(new_nums) # map new_nums = list(map(lambda x: x % 10, nums)) print(new_nums) # Processing of two sequences of map num1 = [23, 8, 90, 2] num2 = [9, 89, 7, 23] # [32,97,97,25] new_nums = list(map(lambda x, y: x + y, num1, num2)) print(new_nums) nums = [23, 8, 90, 2] # Derivation print([i * 10 for i in nums]) # map print(list(map(lambda i: i * 10, nums))) # Exercise 4: given two lists of numbers, create a new sequence with the number of elements in the first list as ten digits and the number of elements in the second list as single digits num1 = [23, 8, 914, 2] num2 = [9, 89, 7, 231] # new_num=[39,89,47,21] print(list(map(lambda x, y: (x % 10) * 10 + y % 10, num1, num2))) # Exercise 5: given that the two lists are student names and ages, create a list that holds multiple student information # [{name ':' Xiao Ming ',' age ': 18}, {name': 'Zhang San', 'age': 21}, {name ':' Li Si ',' age ': 22}, {name': 'Lao Wang', 'age': 19}] names = ['Xiao Ming', 'Zhang San', 'Li Si', 'Lao Wang'] ages = [18, 21, 22, 19] print(list(map(lambda x, y: {'name': x, 'age': y}, names, ages)))
2, Advanced usage of reduce
reduce ----Merge the elements in the sequence into one data according to the specified rules reduce(function,sequence,Initial value) Function requirements: there are only two parameters -----The first parameter points to the initial value, and the second parameter points to each element in the sequence Return value -----Merge method (merge by observing the operation of elements and initial values)
eg:
# Sum of all elements > 118 nums = [10, 20, 32, 56] print(reduce(lambda x, y: y + x, nums, 0)) # Multiplication of all elements > 480 nums = [2, 3, 8, 10] print(reduce(lambda x, y: x * y, nums, 1)) # Merge elements in nums > 23810 nums = [2, 3, 8, 10] print(reduce(lambda x, y: x + str(y), nums, '')) # Exercise 3: merge the elements in names - > 'Xiao Zhang, Li Lao' names = ['Xiao Ming', 'Zhang San', 'Li Si', 'Lao Wang'] print(reduce(lambda x, y: x + y[0], names, '')) # Exercise 4: sum all elements in nums according to the value - > 140 nums = [10, '12', 12.5, '5.5'] print(reduce(lambda x, y: x + float(y), nums, 0)) # Exercise 5: sum all numeric data in nums - > 12 + 100 + 10.5 - > 122.5 # Two methods: using derivation and not using derivation nums = [12, 'abc', '12.5', 100, 10.5] print(reduce(lambda x, y: x + y, [i for i in nums if type(i) in (int, float)], 0)) print(reduce(lambda x, y: x + (y if type(y) in (int, float) else 0), nums, 0)) # Exercise 6: know a list of students students = [ {'name': 'Xiao Ming', 'age': 18, 'math': 90, 'chinese': 85, 'English': 60}, {'name': 'stu1', 'age': 22, 'math': 83, 'chinese': 80, 'English': 30}, {'name': 'stu2', 'age': 30, 'math': 67, 'chinese': 93, 'English': 87}, {'name': 'stu3', 'age': 19, 'math': 55, 'chinese': 76, 'English': 69}, {'name': 'stu4', 'age': 17, 'math': 79, 'chinese': 80, 'English': 90} ] # 1) Seek the average score of class Chinese score print(reduce(lambda x, y: x + y['chinese'] / len(students), students, 0)) # 2) Sort the list from large to small according to the average score of students print(sorted(students, key=lambda x: (x['math'] + x['chinese'] + x['English']) / 3, reverse=True)) # 3) Associate the data in address to each student in turn address = ['Chongqing', 'Chengdu', 'Beijing', 'Kunming', 'Shenzhen'] def temp(stu, addr): stu['address'] = addr return stu print(list(map(temp, students, address)))
Function ---- customize comparison rules (how to compare when determining the size of comparison elements)
There is and only one parameter ---- representing each element in the sequence
There is a return value that determines the comparison rule
3, The essence of function
A function is a variable
To define a function in python is actually to define a variable whose type is function, and the function name is the variable name
variable=lambda Parameter list: return value def Variables (parameter list): Function body return Return value
eg:
def b(): print('Hello function') return c1 = b # c1 function of assigned function print(c1) # Hello function c2 = b() # c2 is the return value of the function print(c2) # None
iterator
1, What is an iter ator
Iterators are container data types -----It can be traversed or converted into lists or tuples The print iterator cannot view elements and cannot count the number of elements in the iterator If you want to get the element of the iterator, you must take the element out of the iterator. Once the element is taken out, the element does not exist in the iterator and cannot be added again
2, Create iterator
# Method 1: use iter to convert other sequences to iterators (any sequence can be converted to iterators) iter1 = iter('hello') iter2 = iter([1, 2, 3, 4, 5, 6]) iter3 = iter({3, 5, 4, 7}) iter4 = iter({'name': 'Xiao Hong', 'age': 18}) print(type(iter1)) # <class 'str_iterator'> print(iter2) # Cannot view element < list_ iterator object at 0x0000028BEE2E6EC8> # print(len(iter3)) # Cannot count the number of typeerrors: object of type 'set'_ iterator' has no len() # Method 2: create a generator # 3. Gets the element of the iterator # No matter how the element of the iterator is obtained, the obtained element must disappear from the iterator
3, Gets the element of the iterator
Note: no matter how the element of the iterator is obtained, the obtained element must disappear from the iterator
1)Get a single element next(iterator ):Gets the topmost element in the iterator each time 2)ergodic for variable in Iterator: Circulatory body
eg:
print(next(iter3)) # 3 print(next(iter3)) # 4 print(next(iter3)) # 5 print(next(iter3)) # 7 # print(next(iter3)) # Error StopIteration exceeded for i in iter4: print(i)
generator
1, What is a generator
A generator is a container -----It can be traversed or converted into lists, elements, etc Instead of saving multiple data, it is an algorithm that generates multiple data The generator has all the characteristics of iterators: elements cannot be seen in printing, the number of elements cannot be counted, and once elements are obtained, the corresponding elements will disappear from the generator
2, Create generator
Call a with yield Keyword function can get a generator If an ordinary function is called, the function body will be executed when calling the function, and the return value of the function will be obtained If the body of the calling function has yield,When calling a function, the function body will not be executed, and the function value will not be obtained. What you get is a generator
eg:
def func1(): yield # Keyword for generator print('=====') print('-----') return 100 result = func1() print(result) # <generator object func1 at 0x0000026CE9AF5148>
3, Control the number and value of data generated by the generator
How many data can be generated by the generator, and what data can be generated by the function body of the function called when the generator is created, Encountered several times during execution yield,And every time yield When I was young yield The following values determine
eg:
def func2(): print('====') yield 1 print('++++') yield 2 return 100 # End the function body when return is encountered yield 3 gent1 = func2() print(list(gent1)) def func3(): for i in range(1, 4): i *= 100 yield i gent2 = func3() # A generator # print(next(gent2)) # 100 # print(next(gent2)) # 200 # print(next(gent2)) # 300 # print(next(gent2)) # report errors # Three generators print(next(func3())) # 100 print(next(func3())) # 100 print(next(func3())) # 100
4, How the generator generates data
It is equivalent to printing the previous value and yield value when the yield stop is encountered during the execution of the function
The next execution starts after the first yield and ends at the next yield
If return is encountered, the function body ends
eg:
Exercise 1: write a function to create Python Student ID generator # 'python001','python002',.... 'python999' def python_id(): for i in range(1, 1000): if i < 10: yield 'python00' + str(i) elif 10 <= i < 100: yield 'python0' + str(i) else: yield 'python' + str(i) stu_id = python_id() print(list(stu_id)) # Exercise 2: write a function to create a generator for the student number of students in a specified subject # python -> 'python001','python002',.... 'python999' # java -> 'java001','java002',.... 'java999' def stu_id_1(class_name): if class_name == 'java': for i in range(1, 1000): if i < 10: yield 'java00' + str(i) elif 10 <= i < 100: yield 'java0' + str(i) else: yield 'java' + str(i) elif class_name == 'python': for i in range(1, 1000): if i < 10: yield 'python00' + str(i) elif 10 <= i < 100: yield 'python0' + str(i) else: yield 'python' + str(i) stu_id = stu_id_1('java') print(list(stu_id))
Use of modules
1, What is a module
A py file is a module, and the module name is the file name of the PY file
2, How to use another module in one module
Premise: only modules whose module name is an identifier and not a keyword can be used by other modules
Principle: import before use
Three. Module classification
System module ----- the python file provided in the python environment
Custom module ---- the py file created by the programmer
4, How to import modules
1)import Module name -----Import the specified module, which can be imported through'Module name.'Use the global variables of this module 2)from Module name import Variable 1,Variable 2,Variable 3,..... -----Import the specified module. After importing, you can directly use the corresponding variables 3)from Module name import * -----Import the specified module. After importing, you can directly use all global variables in the module 4)rename import Module name as New module name -----Rename module from Module name import Variable 1 as New variable name,Variable 2,Variable 3,..... -----Rename variable
eg:
# 1) # import test # print(test.a) # 100 # print(test.b) # True # print(test.func1()) # ----- 100 # 2) # from test import a, func1 # # print(a) # 100 # print(func1()) # ----- 100 # print(b) # Error NameError: name 'b' is not defined
5, Principle of import module
When the code is executed into the import module, the system will automatically enter the import module and execute all the codes in the module
If the same module is imported multiple times in the same program, the code in the corresponding module will be executed only once
6, Select the data and functions that can be imported when importing the module
if __name__ == '__main__': Data that does not need to be imported
Code outside of if will be called
The code in if will not be executed