Python3 3 days of speed introduction five iterators and generator __python

Source: Internet
Author: User
The Python3 iterator and generator iterations are one of the most powerful features of Python and a way to access the elements of a collection.
An iterator is an object that remembers where to iterate. The iterator object is accessed from the first element of the collection until all the elements have been accessed and finished.
Iterators can only move forward and not back.
There are two basic methods for iterators: ITER () and next ().
A string, a list, or a tuple object can be used to create iterators in Python, functions that use yield are called generators (generator).
Unlike a normal function, the generator is a function that returns an iterator that can only be used for iterative operations, and simpler to understand that the generator is an iterator.
During the call to the generator, the function pauses and saves all current running information, returns the value of the yield, and continues from its current position the next time the next () method is executed, each time the yield is encountered.
Invokes a generator function that returns an Iterator object. """ImportSYS #迭代器 list = [1,2,3,4,5,6] Print (' for traversal iterator ') Iter1 = iter (list) forX inIter1:print (x) Print (' whike traversal iterator ') Iter2 = iter (list)While True:Try: Print (Next (iter2), end=" , ")exceptStopiteration:print ("Iterator exception") Break #生成器defFibonacci (N): # generator Function-Fibonacci A, B, counter = 0, 1, 0While True:if(Counter > N): returnyieldA A, B = B, A + b counter + = 1 F = Fibonacci (Ten) # F is an iterator that is returned by the generator to generateWhile True:Try: Print (Next (f), end=" ")exceptStopIteration:sys.exit ()

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.