python iterator generator

1. Generators and iterators. Special functions with yield are generators. Anything that can be used by a for loop is called iterable. And it can be called by _next()_, and it can continuously return value is called iterator

   

2, yield simple generator

#Iterator is simple to use 
print ([i *2 for i in range(10 )])
 print ((i *2 for i in range(10)). __next__ ())


# labo number 
def lab(max):
    a,b,n=0,1,1
    while n< max :
        a,b=b,a+b
        n= n+1
        print(b)
    return 0

lab(10)

# a,b=b,a+b Pay attention to assignment, equivalent to tmp = [b,a+b] ,a= tmp[0],b=tmp[2]
# generator 
# labo number 
def lab(max):
    a,b,n=0,1,1
    while n< max :
        yield b
        a,b=b,a+b
        n= n+1
        print(b)

f=(lab(10))


print(f.__next__())
print(f.__next__())
print(f.__next__())

3. Single-threaded parallel effects, practical application of generators, problems of producers and consumers (prototype of asynchronous IO)

# yield single-threaded parallel asynchronous call 
# producer consumer

def   consumer(name):
     print ( " %s is ready to eat buns " % (name))
     while True:
        baozi = yield 
        print ( " %s starts eating %s " % (name,baozi))
     return  ' done '

def production():
    c1 = consumer( ' xiajinqi ' )
    c2 = consumer('xiaosan')
    c1.__next__()
    c2. __next__ ()   #Two customers are ready to eat buns print ( " laozi starts to make buns " )   #Start to prepare buns for i in range ( 20 ):
    
    
        baozi1 = ' pork stuffing ' 
        baozi2 = ' leek stuffing ' 
        print ( " made a pork stuffing " )
         print ( " made a chive stuffing " )
        c1.send(baozi1)
        c2.send(baozi2)
    return 0

production()

4. Iterator

print(isinstance([ i* 2 for i   in range (10)],Iterator))
print(isinstance(( i* 2 for i   in range (10)),Iterator))

# 3.0 range defaults to iterator

5. Built-in functions

 

print (abs(-10))   #take the absolute value of 10 
print (all([2,0,2])) #if all of the iterable objects are true, return true 
print (all([-1,-1, 2])) #Whether the iterable object is true (one is true) 
print (bin(22)) # 0b10110 The number is converted to binary 
print (callable()) # Determine whether the function can be called

6. Serialization

#serialize import   json _

info = {"name":"xiajinqi","age":18}

f = open("11.txt","w",encoding='utf-8')
data=json.dumps(info)
f.write(data)
f.close()

#序列化
import  json
#info = {"name":"xiajinqi","age":18}

f = open("11.txt","r",encoding='utf-8')
data = json.loads(f.read())
print(data['age'])
f.close()

7、pimple

import  pickle
#info = {"name":"xiajinqi","age":18}


def  login():
    print("hello")

info = {"name":"xiajinqi","func":login}
f = open("11.txt","wb")
f.write(pickle.dumps(info))
f.close()


#序列化
import  pickle
#info = {"name":"xiajinqi","age":18}


def  login():
    print("hello1")

info = {"name":"xiajinqi","func":login}
f = open("11.txt","rb")
data =pickle.loads(f.read())
print(data)
print(data['func']())
f.close()

8\Serialization Note that only loads and dumps can be loaded once

9. Software catalog specification:

"Designing the project directory structure", like "coding style", is a matter of personal style. There have always been two attitudes towards this stylistic norm:

  1. One class of students felt that this personal style issue was "irrelevant". The reason is to make the program work just fine, and the style issue is not a problem at all.
  2. Another class of students believes that normalization can better control the program structure and make the program more readable.

I am more inclined to the latter, because I am a direct victim of the former classmates' thoughts and behaviors. I once maintained a very unreadable project. The logic of its implementation was not complicated, but it took me a very long time to understand what it wanted to express. Since then, my personal requirements for improving the readability and maintainability of the project have been very high. "Project directory structure" actually belongs to the category of "readability and maintainability". We design a clear-level directory structure to achieve the following two points:

  1. High readability: People who are not familiar with the code of this project can understand the directory structure at a glance, know which program startup script is, where is the test directory, where is the configuration file, etc. So that you can understand the project very quickly.
  2. High maintainability: After defining the organizational rules, the maintainer can clearly know which new files and codes should be placed in which directories. The benefit of this is that the size of the code/configuration increases over time and the project structure is not cluttered and still well organized.

Therefore, I think it is necessary to maintain a clear directory structure. What's more, organizing a good project directory is actually a very simple thing.

directory organization

There are already some agreed-upon directory structures on how to organize a good Python project directory structure. In this question on Stackoverflow , you can see everyone talking about the Python directory structure.

It's been said very well here, and I don't plan to reinvent the wheel to list all kinds of different ways. Here I'll talk about my understanding and experience.

Assuming your project is named foo, the most convenient and quick directory structure I suggest is enough:

Foo/
|-- bin/
|   |-- foo
|
|-- foo/
|   |-- tests/
|   |   |-- __init__.py
|   |   |-- test_main.py
|   |
|   |-- __init__.py
|   |-- main.py
|
|-- docs/
|   |-- conf.py
|   |-- abc.rst
|
|-- setup.py
|-- requirements.txt
|-- README

Briefly explain:

  1. bin/: Store some executable files of the project, of course, you can name script/it and so on.
  2. foo/: holds all the source code of the project. (1) All modules and packages in the source code should be placed in this directory. Don't put it in the top-level directory. (2) Its subdirectory tests/stores unit test code; (3) The entry of the program is best named main.py.
  3. docs/: Store some documents.
  4. setup.py: Scripts for installation, deployment, packaging.
  5. requirements.txt: A list of external Python packages that store software dependencies.
  6. README: Project description file.

 

"Designing the project directory structure", like "coding style", is a matter of personal style. There have always been two attitudes towards this stylistic norm:

  1. One class of students felt that this personal style issue was "irrelevant". The reason is to make the program work just fine, and the style issue is not a problem at all.
  2. Another class of students believes that normalization can better control the program structure and make the program more readable.

I am more inclined to the latter, because I am a direct victim of the former classmates' thoughts and behaviors. I once maintained a very unreadable project. The logic of its implementation was not complicated, but it took me a very long time to understand what it wanted to express. Since then, my personal requirements for improving the readability and maintainability of the project have been very high. "Project directory structure" actually belongs to the category of "readability and maintainability". We design a clear-level directory structure to achieve the following two points:

  1. High readability: People who are not familiar with the code of this project can understand the directory structure at a glance, know which program startup script is, where is the test directory, where is the configuration file, etc. So that you can understand the project very quickly.
  2. High maintainability: After defining the organizational rules, the maintainer can clearly know which new files and codes should be placed in which directories. The benefit of this is that the size of the code/configuration increases over time and the project structure is not cluttered and still well organized.

Therefore, I think it is necessary to maintain a clear directory structure. What's more, organizing a good project directory is actually a very simple thing.

directory organization

There are already some agreed-upon directory structures on how to organize a good Python project directory structure. In this question on Stackoverflow , you can see everyone talking about the Python directory structure.

It's been said very well here, and I don't plan to reinvent the wheel to list all kinds of different ways. Here I'll talk about my understanding and experience.

Assuming your project is named foo, the most convenient and quick directory structure I suggest is enough:

Foo/
|-- bin/
|   |-- foo
|
|-- foo/
|   |-- tests/
|   |   |-- __init__.py
|   |   |-- test_main.py
|   |
|   |-- __init__.py
|   |-- main.py
|
|-- docs/
|   |-- conf.py
|   |-- abc.rst
|
|-- setup.py
|-- requirements.txt
|-- README

Briefly explain:

  1. bin/: Store some executable files of the project, of course, you can name script/it and so on.
  2. foo/: holds all the source code of the project. (1) All modules and packages in the source code should be placed in this directory. Don't put it in the top-level directory. (2) Its subdirectory tests/stores unit test code; (3) The entry of the program is best named main.py.
  3. docs/: Store some documents.
  4. setup.py: Scripts for installation, deployment, packaging.
  5. requirements.txt: A list of external Python packages that store software dependencies.
  6. README: Project description file.

Guess you like

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