Summary of generator and file system knowledge of Python basic learning


1、 Generator

First, explain the iterator.

The ability to iterate over sequences in a consistent way (such as objects in a list or lines in a file) is an important feature of Python. This is achieved through a method called iterator protocol, which is a general way to make objects iteratable

Now, a native method of making objects iteratable.

some_ dict = {"a": 1, "b": 2, "c": 3}  

An iterator is a special object that can be passed to a Python interpreter in a context such as a for loop. Most methods that accept objects such as lists can also accept any iteratable object. For example, built-in methods such as min, Max, sum, and type constructors such as list and tuple.

dict_ iterator=iter(some_dict)

A generator is a simple way to construct new iteratable objects。 General functions only return a single value after execution, while the generator returns a value sequence in a delayed manner, that is, it pauses after each value is returned until the next value is requested. To create a generator, simply replace return in the function with yeild.

def squares(n=10):


<generator object squares at 0x7f3a75af4a00>
Generating squares from 1 to 100

Another more concise way to construct a generator is to use generator expression. This is a generator similar to list, dictionary, set derivation. AttentionThe creation method is to change the square brackets at both ends of the list derivation formula into parentheses:

gen=(x**2 for x in range(5))

2、 File system

The built-in open function parameters are as follows:

Summary of generator and file system knowledge of Python basic learning

Common file methods

Summary of generator and file system knowledge of Python basic learning

#With the statement, you can easily clean up the open file and automatically close the file stream when the run is almost finished

with open(path) as f: 
    lines=[x.strip() for x in f]

This is the end of this article on the summary of Python basic learning generator and file system knowledge. For more information about Python generator and file system, please search the previous articles of developepper or continue to browse the relevant articles below. I hope you will support developepper in the future!