Advanced Features of Python (2)

1. List Compilation

1. Generate the full permutation of abc and def

2, 1) Output the names in the list and capitalize the first letter


2) When the names in the list are illegal characters, output the names in the list and capitalize the first letter


3. Find the files ending with .log in the specified directory

import os module 

os.listdir(file name) View all files under the directory



2. Generator

Why do you need generators?

Through list comprehension, we can directly create a list, subject to memory constraints, the capacity of the list is definitely limited; save memory through generators.

Through the generator, the subsequent elements are continuously calculated during the loop process, so that it is not necessary to create a complete list, which saves a lot of space. In python, this mechanism of computing while looping is called a generator.

example:

1. Fibonacci sequence (the latter number is equal to the sum of the first two numbers)

Generate 6 Fibonacci sequences _


In the function, add the yield keyword, when the function with the yield keyword is called, the generator returns


How yield works: When the g.next() method is called, the function is executed, and the execution stops when it encounters yield; execute g.next() again


2. How to access the generator content
1
) g.next() method = next(g); several calls are required ;
.next():
run the generator function, stop when yield is encountered, next() again
.send( )
Pass the value to the generator function to realize the interaction with the generator. You can receive the value through a variable in front of the yield of the function. close
:
close the generator, and the next method cannot be called; otherwise, an error StopItertion ( the iterator has been stopped ) is reported
. throw:
Send an exception to the generator;
what is an exception: NameError, ZeroDivisionError.....




Third, the generator application

Producer-Consumer Model

1. Sell buns

consume function = yield; is a generator function

c1.next() stops at the line kind = yield


2. Add a chef on the basis of 1)

cunsumer and produce function = yield; is the generator function


3. Mini Chatbot



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324504057&siteId=291194637