Python (Day8) iterator, generator

Source: Internet
Author: User

What is Iteration 1 repeat 2 the next repetition is based on the last result
# while true:#     cmd=input (' >>: ') #     print (cmd) # l=[' A ', ' B ', ' C ', ' d ']# count=0# while Count < Len (l): #     print (L[count]) #     count+=1## l=[' A ', ' B ', ' C ', ' d ']# for count in range (Len (L)): #     print (L[count]) # d={' a ': 1 , ' B ': 2, ' C ': 3}## for k in d:#     print (k)

Python in order to provide an iterative way that does not depend on the index,
Python will have built-in __iter__ methods for some objects
Obj.__iter__ is called an iterative object

Two iterative objects: obj.__iter__ three iterators: iter1=obj.__iter__ () 1 iter1.__next__2 iter1.__iter__ iter1.__next__ ()

Advantages of Iterators
1: Provides an index-independent way to take a value
2: Lazy calculation. Save Memory

Disadvantages of iterators:
1: value is not as easy as index value
2: Disposable. You can only walk backwards, not backwards.
3: Unable to get length

L=[1,2,3]FOR item in L: #i =l.__iter__ ()    print (item)
l=[' x ', ' y ', ' z ']# print (l[2]) # print (l[0]) # i=l.__iter__ () # Print (i.__next__ ()) # Print (i.__next__ ()) # Print (I.__next_ _())

  

#得到的迭代器: Both __iter__ and a __next__ method # d={' A ': 1, ' B ': 2, ' C ': 3}## i=d.__iter__ () #i叫迭代器 # Print (i) # print (i.__next__ ()) # Print (i.__next__ ()) # Print (i.__next__ ()) # Print (i.__next__ ()) #StopIteration

  

  

Iterator determines whether an iterator object iterabl is required to iterate over the object as an iterative object. __iter__ () is converted to an iterator to iterate over an iterator object that can iterate the iterator directly to the application: 1 provides a unified iterative Method 2 lazy computation that does not depend on the index, For example, to fetch each line of a file

Iv. generator 1, generator function: The function body contains the yield keyword, the result of which the function executes is the generator

def foo ():    print (' first------> ')    yield 1    print (' second-----> ')    yield 2    print (' Third-----> ')    yield 3    print (' fouth-----> ') g=foo ()

2, the generator is an iterator

 

# Print (g.__next__ ()) # Print (g.__next__ ()) # Print (g.__next__ ()) # Print (g.__next__ ()) # for I in G: #obj =g.__iter__ () # Obj.__next__ () #     print (i)

3.

Yield Features:
1. Similar to return, you can return a value, but the difference is that yield returns multiple values, and return can only return one value at a time
2. Encapsulates the __iter__ and __next__ methods for the function, and makes the result of the function's execution an iterator
3. Follow the value of the iterator obj.__next__ (), the execution of the triggered function, the function pause and the continuation of the state are saved by yield

def countdown (n):    print (' Starting countdown ') while    n > 0:        yield n        n-=1    print (' Stop Countdown ' ) G=countdown (5) # Print (g) # Print (g.__next__ ()) # Print (g.__next__ ()) # Print (g.__next__ ()) # Print (g.__next__ ()) # Print (g.__next__ ()) # Print (g.__next__ ()) # # for I in g:#     print (i)

Examples:

#1 write tail-f a.txt |grep ' error ' |grep ' 404 ' command, Monday Dictation import timedef Tail (filepath,encoding= ' Utf-8 '): With    open (Filepat H,encoding=encoding) as F:        F.seek (0,2) while        True:            line=f.readline ()            if line:                yield line            Else:                time.sleep (0.5) def grep (Lines,pattern): for-line in-    lines:        if pattern in line:            #print (line)            Yield Lineg1=tail (' a.txt ') g2=grep (G1, ' Error ') G3=grep (G2, ' 404 ') For i in G3:    print (i)

Summarize:

1. An iterator protocol means that an object must provide a next method that either returns the next item in the iteration, or causes a Stopiteration exception to terminate the iteration (only backward cannot go forward)

2. An iterative object: An object that implements an iterator protocol (how to: Define an __iter__ () method within an object)

3. The Protocol is a convention that iterates over an object, implements an iterator protocol, and Python's internal tools (such as a For loop, Sum,min,max function, etc.) use an iterator protocol to access an object.

The nature of the 4.for loop: Loop through all objects, all using an iterator protocol.

5. (Strings, lists, tuples, dictionaries, collections, file objects) These are not iterative objects, but in the for loop, they call their internal __iter__ method, turning them into an iterative object

The For loop then calls the __next__ method of the iteration object to fetch the value, and the for loop catches the stopiteration exception to terminate the iteration

6. Generator: Can be understood as a data type, this data type automatically implements the iterator protocol (other data types need to call their own built-in __iter__ method), so the generator is an iterative object

7. Can be understood as a data type, this data type automatically implements the iterator protocol (other data types need to call their own built-in __iter__ method), so the generator is an iterative object

8. Why use Generator Builder's advantages

Python provides support for deferred operations using the generator. The so-called deferred operation refers to producing results when needed, rather than immediately producing results. This is also the main benefit of the generator.

9. Generator Summary:

1). is an iterative object

2). Delay calculation is realized, save memory Ah

3). The generator is essentially the same as the other data types, all of which implement the iterator protocol, except that the generator attaches a delay to compute the benefits of saving memory, and the rest of the iterative objects do not have this benefit

Python (Day8) iterator, generator

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: info-contact@alibabacloud.com 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.