Python iterators and generators

Source: Internet
Author: User

Iterators:

An object that can directly act on a for loop is called an iterative object: iterable

An object that can be called by the next () function and continually returns the next value is called an iterator: Iterator

Characteristics:

1. The visitor does not need to be concerned about the structure inside the iterator, but to continue to fetch the next content through the next () method

2. A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end

3. You can't go back halfway through the interview.

4. Easy to recycle large data collection, save memory

Generator:

When a function call returns an iterator, the function is the generator, and if the function contains the yield syntax, the function becomes the generator and the generator is a special iterator.

Characteristics:

1. Not all results are generated at once, only one result is returned at a time

2. Reduce memory usage by not having to prepare all the elements throughout the iteration

3. Only one time can be traversed

Example:

1. Add () outside the for loop to make it a generator


With Next (g) to get each value, get the last element, then call the stopiteration error, can be handled by snapping, a better way is to use a for loop, because generator is also an iterative object, No need to care about Stopiteration's mistakes.

2. Using yield to implement the Fibonacci sequence

deffib (max): N, a, b= 0, 0, 1 whileN <Max:yieldA, b## GeneratorA, B = B, A +B N+ = 1return "---done---"defMain (): G= FIB (6)     forIinchg:Print(i[0],i[1])if __name__=='__main__': Main ()

3. Using the generator to implement the parallel effect of the threads

Import TimedefConsumer (name):Print("%s ready to grab red envelopes"%name) whileTrue:money=yield        Print("The red Envelope [%s] came and was robbed by [%s]"%(Money, name))defproducer (name): C1= Consumer ('A') C2= Consumer ('B') C1.__next__() c2.__next__()    Print("Getting ready to send out red envelopes")     forIinchRange (10,15): Time.sleep (1)        Print("sent a red envelope, divided into two") c1.send (i) c2.send (i)if __name__=="__main__": Producer ("Wangzai")

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.