python-- iterative and analytic

In general, the builder and general functions as, and actually using conventional def written statement. However, when creating, he automatically iteration protocol so that it can appear in the iteration background.

0. iteration agreement

There __next__ method of the object will advance to the next result, when it reaches the end StopIteration exception is thrown. In python, any such objects are considered to be iterative. Any such objects can also be a for loop to iterate tools or other iteration, because all iterations of internal tools are working together to call __next__ in each iteration, and catch StopIteration exception to determine when to leave.

# Read a text file is the best way not to read at all; instead of the approach is to allow for the cycle automatically call next round in order to advance to the next line 
# This is the best way to read a text file, because the wording of the easiest , run the fastest, and the memory usage is also the best. 
# This is for line in f.readlines and effect a 
L = List () 
with Open ( ' ../data/123.txt ' ) AS F:
     # A = f.readline () 
    for Line in F:
         Print (Line , End = '' )   # End = '' in order to suppress a \ n as it has a \ n the 
        l.append (Line)
     Print (L)

 

1. Manual iteration: iter and next

python3 provides a built-in function method __next__ next, it will automatically call an object. Given a iterable X, calls the next (X) is equivalent to .__ Next __ X-() .

Manual iterative method is to create an iterator (iter), and then iterate through the next method iterator. Specifically, the following:

D = {'a':'A','b':'B','c':'C'}
I = iter(D)
print(next(I)) # a
print(next(I)) # b

But for the file, it is not required to initialize the iterator (second line of code above), because the file object is its own iterator. In other words, it has its own method of __next__ file , so no return like a different object. Lists, and many other built-in objects, not their own iterators, because they support multiple open iterators. For such objects, we must call to start the iteration iter, they (dict, list) do not own __next__ method :

  

D = { ' A ' : ' A ' , ' B ' : ' B ' , ' C ' : ' C ' } 
the I = ITER (D)
 IF ITER (D) IS D:
     Print ( ' to true ' )
 elif ITER ( D) iS the I:
     Print ( ' the I iS iter ' ) # I thought it would print this one, the result is not, and do not know why
 the else :
     Print ('dict dont have __next__ func')  # print this one
f = open('../data/123.txt')
print(f.__next__())
if iter(f) is f:
    print('TRUE')  # print this one 

 

2. list comprehension

For example, the following code is a list of common resolve:

L = range(10)
L = [x + 10 for x in L]  # [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Readlines method in the file once it can load the file to a list of line strings, this effective but at the end will contain a line break . Remove the line breaks, and saved to a list of the following wording:

= Lines [line.rsplit () for Line in Open ( ' 123.txt ' )] # rsplit reverse strips spaces (line feed)

Increased testing and analytical list of nested loops:

[x for x in range(5) if x %2 ==0]  # [0, 2, 4]
list(filter((lambda x: x % 2 ==0), range(5)))  # [0, 2, 4]

More complex points:

list(map((lambda x: x**2), filter((lambda x: x %2 ==0),  range(10))))
# [0, 4, 16, 36, 64]

Matrix used:

M = [[1,2,3],
     [4,5,6],
     [7,8,9]]

[row[1] for row in M]  # [2,5,8]

 

3. Understand Resolution List

Advantages: map calls to two times faster than the equivalent of a for loop, while the list comprehension tend to be slightly faster than the map of some calls. Speed ​​gap from the underlying implementation, map and list are parsed in the interpreter language C at a speed to run than the python for loop code much faster in the stepping operation PVM.

Cons: parsing a list and map for circular logic is not clear.

 

4. Generator

Generator function: def statement written as a conventional, but the use of a yield statement returns a result, suspend and resume their state between each result.

Generator expressions are similar to a list comprehension, but they return an object to produce results on demand, instead of building a list of results, grammatically speaking, generator expressions like a general list of parsing the same, but they are enclosed in in parentheses instead of square brackets.

 

Since both do not build a list of one-time, which saves memory space, and allow time for computation result request to each dispersion.

 

4.1 generator function: yield VS return

Suspend state

And a return value and the routine exits of different function, generator function and continue call is automatically suspended at the time of execution of the generated value.

The main differences between the code generators and general functions in that the generator yields a value, instead of a return value. The yield statement suspending the function and the caller is sent back to a value (return directly return the results and concluded this func), but retain enough state so that functions can continue from where it left off. When continue, continue to function immediately after a yield return.

Iterative integration agreement

Iterative protocol: iterations can __next__ object defines a method, it either returns the next iteration, or initiate a special stopIteration exception to terminate iteration. Used iterations iter built-in function to accept an object.

Method: If the function contains statements yield (note that the statement is not a function), this statement will be prepared as a generator. That automatically iterator protocol. When the call generator, it returns an iterator object that supports a method called __next__ automatically created to continue the implementation of the interface. Call generator may also have a return statement, always at the end of a block of statements def, direct termination of the generated value. Technically, any conventional function can later withdraw, triggering a stopIteration an exception to achieve.

Function Generator application

def a(n):
    for i in range(n):
        yield i ** 2

for i in a(5):
    print(i, end=':')  # 0:1:4:9:16:

x = a(5)
print(type(x))  # generator
print(x.__next__())  # 0
print(next(x))  # 1
print(next(x))  # 4

Extended protocol generator function: send and next

Then update

 

Guess you like

Origin www.cnblogs.com/SsoZhNO-1/p/11448118.html