Python Tour: iterators

Source: Internet
Author: User

1. What is an iterator?

Iterators are a repeating process, and each repetition is the result of an opportunity's last

Want to know exactly what an iterator is? You must first understand the concept of what is an iterative object?

Iterate objects: In Python, any object with a built-in __iter__ method is an iterative object

The following are objects that can be iterated: (You can do it yourself behind the object. _ See if there is __iter__) str='Hello'List=[1,2,3]tup={1,2,3}dic={'x': 1}s1={'a','b','C'}f=open ('a.txt','W', encoding='Utf-8')

2. iterators

Iterator: An iterative value tool that iterates over an object by executing the __iter__ method The resulting return value is the iterator object

dic={'x': 1,'y': 2,'Z': 3}iter_dic=dic.__iter__()#The first thing is to get an iterator that calls the __iter__ () functionPrint(Iter_dic.__next__())#The second thing is the loop process, which calls the __next__ () function. Print(Iter_dic.__next__())Print(Iter_dic.__next__())
print (iter_dic.  __next__ ())  #第四行会提示哦, also equivalent to an error, only three values, you take the fourth value of the time will stop the iteration
# Print (iter_dic.__next__ ())
Stopiteratio
4. An iterative object vs iterator object?
objects that can be iterated: str,list,tuple,dict,set,file
1. Get a way to iterate objects: Python built-in Str,list,tuple,dict,set,file are iterative objects

2, Features: The built-in __iter__ method is called an iterative object, the execution of this method will get an iterator object.
Iterator object: The file object itself is an iterator object
1. How to get an iterator object:
Executes the __iter__ method of an iterative object, and the returned value is the iterator object
2. Features:
Built-in with the __next__ method, executing this method will get a value from the iterator object
There is a built-in __iter__ method that executes this method to get the iterator itself
str1='Hello'List1=[1,2,3]tup1= (A) DiC={'x': 1}s1={'a','b','C'}#The file itself is an iterator objectF=open ('a.txt','W', encoding='Utf-8') F.__next__()
5. Analysis of the advantages and disadvantages of iterators

Advantages of iterators:

Provides a way to take a value that does not depend on the index

Iterators Save more memory

Disadvantages of iterators:

Value trouble, can only one take, can only be taken back

And it's a one-time, can't get the length with Len

1, provides a method that does not depend on the index to take the value
#This is the content of the A.txt fileADADAAASDASDDASDASDASL=open ('a.txt','R', encoding='Utf-8') ITER=l.__iter__() whileTrue:#dead Loop Try:#Use this parameter to detect Print(ITER.__next__(), end="') exceptStopiteration:#detect when a stopiteration appears Break #to detect the presence of stopiteration, break
L.close ()
#结果如下
Adadaaasdasd
Dasdas
Das
#没有报错

2. Iterators Save more memory
item=Range (0,100000000000000000000000000000000000000000000)  #如rang, Python2 will print 1,2,3,4,5,6 in turn .... Python3 optimized iterators are printed directly, so more memory is saved

Print (item)
#结果如下
Range (0, 100000000000000000000000000000000000000000000)
#value trouble, can only one take, can only be taken backx=[1,2,3]iter_x=x.__iter__() whileTrue:Try:        Print(iter_x.__next__())    exceptstopiteration: BreakPrint('================================= of the second time') iter_x=x.__iter__() whileTrue:Try:        Print(iter_x.__next__())    exceptstopiteration: Break#The results are as follows123second time================================="123
6. For loop principle Analysis:
#6.1. The For loop is called an iterator loop, and the in followed must be an iterative object#6.2, the For loop executes the __iter__ method of the In object, and gets the iterator object#6.3. Then call the iterator object's __next__ method, get a return value assigned to line, execute a loop body#6.4, cycle, until the value is complete, the for loop will detect an abnormal auto-end loopL=open ('a.txt','R', encoding='Utf-8') forLineinchL#iter_l=l.__iter__ ()    Print(line,end="') forIteminch{'x': 1,'y': 2}:    Print(item,end="')#The results are as followsAdadaaasdasddasdasdasxy

Python Tour: iterators

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.