The iterator and generator of the Python function chapter (4)

Source: Internet
Author: User
Tags file handling

1. "B-mode" for file operation (supplemental)

In the last article, I wrote some of the methods of file handling in the final section, but I think it is necessary to mention the following:

Like RB, WB, AB This mode, is in the form of byte operation, need to pay attention to the following several questions:

1) files can not be saved in memory, can only be saved on the hard disk, in binary form, Python can only write strings to a text file, to store value data in a text file, you must first use the function str () to convert it to a string format.

2) When opening a file with a code such as RB. RW, you cannot define the encoding type, that is, you cannot specify encoding within the open () function. Add some additional file operation methods, as follows:

with open ("Nicholas Zhao Si", "wb") as f:
    f.encoding () #Open encoding of the file, encoding = "" defines which encoding method is output, which encoding method is output, regardless of the encoding method of the source file
    #If you do n’t know the encoding of the source file, you can set encoding = ”latin-1” when defining it, this encoding method is compatible with most encodings
    # f.flush () #Refresh, when modifying the file, this method can make the changes take effect (pycharm does not need this method because the internal mechanism of pycharm is automatically saved)
    # f.tell () #Print the cursor position, the cursor movement is in bytes, read () is in characters, 3 bytes in Chinese, 1 byte in English
    #with open ("Nicholas Zhao Si", "w", encoding = "utf-8", newline = "") as f: read the real newline character in the source file,
 Read the file through the readlines method, without newline = "", output \ n, plus \ r \ n
    # (0) #Specify the position of the cursor, at 0
    # (10,0) #Behind is the default position, that is, the cursor position starts from 0 and operates in b mode, because seek moves the cursor in bytes.
    # (10,1) # 1 represents the relative position
    # (3,1) #Move the cursor based on 10
    # (-5, 2) # 2 specifies the cursor position in reverse order
    # f.truncate (10) #Intercept from the beginning to 10 (cursor position) w \ w + mode does not work 
2. File path

If the program file is stored under the current path, the file can be opened by means of open ("file name"), but if the program file is stored under another path or in the subdirectory of the current file, the file path must be provided, which allows Python to be found in a specific location on the system.

  Relative path

If: There is a files file under the current path, the files file has a "Nicholas Zhao four" This program file, if I want to open this file, you need to use a relative file path to open it.

with open ("files \ Nicholas Zhao Si", encoding = "utf-8") as f:
     print (f.readlines ())

This line of code lets Python open the folder files under the "Nicholas Zhao four" This file, in the Windows system, the file path uses the backslash (\) instead of the slash (/)

  Absolute path

  You can tell python exactly where the file is in your computer, so you don't have to worry about where the program you are running is stored, which is called an absolute path. An absolute path can be used when a relative path is not feasible. Absolute paths are usually longer than relative paths, similar to that in Linux systems:/home/dir/files/1.txt; Similar to this in a Windows system: C:\Users\dir\files\1.txt

By using an absolute path, you can read files anywhere in the system.

3. iterators

The difference between iterators and recursive functions: Recursive functions are repeated calls to themselves, must have a clear condition, and each deeper layer of the cycle, the scale must be smaller than before, iterators, each cycle depends on the previous results.

Iterator protocol: An object must provide a _next_ () method that either returns the next item in the iteration or causes a Stopiteration exception (which can only be moved backwards).

An iterative object: An object that implements an iterative protocol (how to implement it). An _iter_ () method is defined inside the object.

A protocol is a convention that iterates through an iterator protocol, and Python's internal tools (such as for loops, sum,min,max functions, and so on) use an iterator protocol to access an object.

Example for a For loop: The For loop follows the iterator protocol to loop through all the objects, (lists, dictionaries, strings, tuples, collections) These are not actually iterative objects, except that in the For loop, they call their internal _iter_ methods and turn them into an iterative object. The For loop then calls the iterator object, and then it can call the _next_ () method until the end of the exception, explained in code as follows:

name=[1,2,3] For i in Name:         l=name.__iter__ ()   print (l.__next__ ()) Print (i)

In the For loop list, essentially the built-in method called the list _iter_ (), the list becomes an iterative object, and after it becomes an iterative object, the list has the _next_ () method, which is called one read at this method.

There is also a next () method, which essentially calls the _next_ () function.

An object that can be called by the next () function and continually returns the value of the next value is an iterator: Iterator, List, dictionary these basic data types, although they are iterative objects, are not iterators, which can be made into iterators by the _iter_ () method.

name = [1,2,3]
print (type (name .__ iter __ ())) turns an iterable object into an iterator through the _iter_ method
operation result:
<class ‘list_iterator’>
4. List-generated and ternary operations

List generation How to say, is a kind of loading force dedicated bar, I give a simple example, I now demand is output from 1-9 of the number, of course, most people will first think of the For loop

name = []
for i in range (10):
     name.append (i)
print (name)
operation result:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The above example does not explain much, seriously read my previous blog, this is very simple for the loop, but if I am too troublesome, this code too much, I will write in one line, can I do it?

print ([i for i in range (10)])
operation result:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

OK, reload version, this is the list expression.

So what is ternary computing?

name = "Nicholas Zhao Si"
print ("Hip-hop dance" if name == "Nicholas Zhao Si" else "Can't hip-hop dance") One yuan: "Hip-hop dance" Binary: Judgment by if statement Ternary: "No hip-hop dance"
Output results:

In fact, it is well understood that the if front can be understood as the return result that evaluates to true, else is the return result that evaluates to False, this is the ternary operation.

Ternary operations can also be used in conjunction with list generation, requirements: output 10 or more than 5 of the number

print ([i for i in range (10) if i> 5])
operation result:
[6, 7, 8, 9] 

But note that in this statement, you can not at home else, must pay attention to ternary, plus else will become four yuan, the program will error

5. Generator

In Python, a mechanism called the generator (generator) that loops one side of the computation. The generator can be understood as a data type that automatically implements the iterator protocol (other data types are called by their own built-in method _iter_ method), so the generator is an iterative object, and the _next_ () method can be used directly.

The representation of the generator classification in Python (Python has two different ways of providing generators)

1. Generator expression, the generator is actually the list generator [] into (). That is, the list generated above, and I'm going to turn it into a generator:

print (type ((i for i in range (10) if i> 5)))
operation result:
<class ‘generator’> 

Generator is the algorithm that is saved, each callnext(),就计算出下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。

a = (i for i in range (10) if i> 5)
print (a .__ next__)
print (next (a)) Each time next () is performed, only one value is read
print (next (a))
operation result:
<method-wrapper ‘__next__’ of generator object at 0x000001620ECD7888>

What if the generator has more than n values? It is obviously inconvenient to use next (), so it is generally used for loops.

2. Function-Generated

As long as the function is defined, return () is changed to yield (), and yield () saves the position of the last read value, and when called again, it starts at that position. A normal functionreturnreturns when it encounters a statement or the last line of a function statement. The function that becomes generator, executes at each invocationnext(), encounters ayieldstatement return, and executes again from the last statement returnedyield.

def func ():
     yield 1
     yield 2
res = func ()
print (res .__ next __ ())
operation result:

Execute the _next_ () method once, output 1, the program stays in this position, when the _next_ () method is executed again, the execution starts at 1, and then outputs 2, which is the function generation. When execution _next_ () reads the complete element, executing the program again throws a Stopiteration exception, and the way I handle the exception is described in detail in the next article.

The iterator and generator of the Python function chapter (4)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.