Python Development function Advanced: An iterative & iterator & Generator

Source: Internet
Author: User

One, an iterative & iterative object

1. The value of one is an iterative iterable
#str List Tuple Set Dict
#可迭代的--The corresponding Mark __iter__

2. Determine if a variable is not an iterative

# print (' __iter__ ' in Dir (list))
# print (' __iter__ ' in dir ([+)])

3. Iterative protocol--there is a __iter__ method in the interior of any iteration

Second, iterators

1. Converting an iterative to an iterator

1 #!/usr/bin/env python2 #_*_coding:utf-8_*_3 4 #iterator #迭代器5 #iterator iterable# iterative objects6L = [1,2,3,4,5]7  forIinchL:8     Print(i)9 Print(ITER (L))#built-in function iter = = L._iter_ ()TenL.__iter__() OneL_iterator =iter (L) A Print(Set (dir (l_iterator))-Set (dir (l))) - Print(Next (L_iterator))#The iterator is going to use the next method to take the value

2. Iterator Summary

#迭代器里既有iter方法, and next method--iterator protocol
The result of #通过iter (O) is an iterator,
#o是一个可迭代的

#迭代器 are mostly used inside python, and we'll just use them.
#迭代器: Built-in __iter__ and __next__ methods

1 #!/usr/bin/env python2 #_*_coding:utf-8_*_3 4L = [1,2,3,4,5]5L_iterator =iter (L)6 Print(L_iterator.__next__())7 Print(L_iterator.__next__())8 Print(L_iterator.__next__())9 Print(L_iterator.__next__())Ten Print(L_iterator.__next__()) OneNext (L_iterator)#==l_iterator.__next__ () A #While True: Write your own equivalent for loop - #Try: - #print (Next (l_iterator)) the #except stopiteration: - # Break

3. An easy way to determine whether it is an iterator or an iterative object

1 #!/usr/bin/env python2 #_*_coding:utf-8_*_3 4  fromCollectionsImportiterable5  fromCollectionsImportIterator6 #s = ' abc '7 #Print (Isinstance (s,iterable)) s is not an iterative object8 #Print (Isinstance (s,iterator)) s is not an iterative object9 #Print (Isinstance (ITER (s), Iterator))

4. Iterators and iterators

#不管是一个迭代器还是一个可迭代对象, you can use the For loop to traverse
#迭代器出现的原因 Save Memory for you

Third, generator

#生成器函数
#生成器的本质就是迭代器

1 #!/usr/bin/env python2 #_*_coding:utf-8_*_3 4 deffunc ():5     Print('AAAA')6A = 17     yieldA#returns the first value8     Print('bbbb')9     yield12#returns a second valueTen #error value, equivalent to three new generators One #G1 = func () A #g2 = func () - #g3 = func () - #Print (Next (func))) #取第一个值 the #Print (Next (func))) #取第二个值 - #Print (Next (func))) #取第三个值 will error because there is no third value - #The correct value is the same generator - #ret = func () #拿到一个生成器 + ## Print (ret) - #print (Next (ret)) #取第一个值 + #print (Next (ret)) #取第二个值 A #print (ret) #取第三个值 An error because there is no third value

3,1 Generator Make clothes instance

1 #/usr/bin/env python2 #_*_coding:utf-8_*_3 4 defMake_cloth ():5      forIinchRange (2000000):6         yield "Item %s Dress"%I7 #szq = Make_cloth ()8 #print (Next (SZQ))9 #print (Next (SZQ))Ten # One #print (Next (SZQ)) A #For i in range: - #print (Next (SZQ))

3.2 Listening to a file instance

1 #!/usr/bin/env python2 #_*_codinglutf-8_*_3 4 #Listening file tail-f5 Import Time6 deftail (filename):7 With open (filename) as F:8F.seek (0, 2)#count from the end of the file9          whileTrue:Tenline = F.readline ()#read new lines of text in a file One             if  notLine : ATime.sleep (0.1) -                 Continue -             yield Line the  - #For line in tail (' Tmp_file '): - #print (line,end = ")

3.3 Calculating the moving average

1 #!/usr/bin/env python2 #_*_coding:utf-8_*_3 4 #average annual income for the year of 7th5 defAverager ():6Total =07Day =08Avrage =09      whileTrue:TenDay_num =yieldAvrage#return Avrage OneTotal + =Day_num ADay + = 1 -Avrage = total/ Day -  the #avg = Averager () - #num = Next (avg) #激活生成器 avg.send (), nothing like send and next effect - #print (avg.send) #传值 next - #print (Avg.send )

3.4 Builder with Adorner

1 #!/usr/bin/env python2 #_*_codinglutf-8_*_3 4 defWrap (func):5     defInner (*args,**Kwargs):6g = func (*args,**Kwargs)7 Next (g)8         returng9     returnInnerTen  One @wrap A defAverager (): -Total =0 -Day =0 theAvrage =0 -      whileTrue: -Day_num =yieldAvrage#return Avrage -Total + =Day_num +Day + = 1 -Avrage = total/ Day +  A #g = Averager () at #Print (G.send (ten)) - #print (G.send )

Python Development function Advanced: An iterative & iterator & Generator

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.