Python iterators and generators

Source: Internet
Author: User

First, iteration

1. Repeat

2. The next repetition is based on the last result

Second, iterators

In order to provide an iterative approach that does not depend on the index, Python will build a __iter__ method for some objects, obj.__iter__ is called an iterative object, obj.__iter__ The result is an iterator, the resulting iterator has both __iter__, There is also a __next__ method

D={' A ': 1, ' B ': 2, ' C ': 3}i=d.__iter__ () #i叫迭代器print (i.__next__ ())

Iii. advantages and disadvantages of iterators

1. Advantages:

1) provides a way to not rely on the index to take a value

2) lazy calculation, save memory

2. Disadvantages

1) value is not as easy as index value

2) One-time, can only go backward can't push forward

3) Unable to predict length

Iv. Generators

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

2. The generator is an iterator

def foo ():    print (' First----------> ')    yield 1    print (' Second----------> ')    yield 2    print (' Third----------> ')    yield 3    print (' Fouth----------> ') g=foo () print (g.__next__ ()) print (g.__next__ ()) Print (g.__next__ ()) print (g.__next__ ())
Yield Features:
1. Similar to return, can return a value, but the difference is that yield returns multiple values, and return can only return once
2. Encapsulate the __iter__ and __next__ methods for the function, the result of the function is made into an iterator
3. Follow the value of the iterator obj.__next__ (), the execution of the triggering 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) for I in G:    print (i)

  

The effect of Send:

1. Pass a value for the yield of the paused position, and yield the value to X

2. As with the next function

Expression of yield in the form of an application

#应用: Grep-rl ' root '/etcimport osdef init (func): Def wrapper (*args,**kwargs): G=func (*args,**kwargs) Next (g) return G return wrapper# stage one: Find the absolute path of the file recursively, send the path to phase two @initdef search: ' Search file Abspath ' while T Rue:start_path=yield g = Os.walk (Start_path) for Par_dir, _, Files in G: # Print (Par_dir, files) for file in Files:file_path = R '%s\%s '% (par_dir, file) target.send (file        _path) #阶段二: Receive file path, open file Get object, send file object to phase three @initdef opener (target): ' Get file Obj:f=open (filepath) ' while True: File_path=yield with open (file_path,encoding= ' utf-8 ') as F:target.send ((file_path,f)) #阶段三: Receive file object, for loop read            Take each line of the file and send the contents of each line to phase four @initdef cat: ' Read file ' while true:filepath,f=yield for lines in F: Res=target.send ((filepath,line)) If res:break# stage four: Receive a line of content to determine if root is in this row, if so, then send the file name to stage five @i Nitdef grep (Target,patteRN): ' grep function ' tag=false while True:filepath,line=yield tag #target. Send ((filepath,line)) Ta    G=false if pattern in Line:target.send (filepath) tag=true# phase five: Receive file name, print result @initdef printer (): ' Print function ' while True:filename=yield print (filename) start_path1=r ' F:\python file \day22\a\b ' start_p Ath2=r ' F:\python file \day22\a ' G=search (Opener (Cat (grep (printer (), ' Root ')) # print (g) # G.send (start_path1) g.send ( START_PATH2)

  

Python iterators and generators

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.