Python Development function Advanced: An iterative & iterator & Generator

Source: Internet
Author: User

One, an iterative

#iterable an iterative
#str
#列表
#tuple
#set
#dict

#可迭代的--The corresponding Mark __iter__
# print (' __iter__ ' in dir ([+)]) #判断一个变量是不是一个可迭代的

Iterative conversion to iterator method

1 #!/usr/bin/env python2 #*_*_cod:utf-8_*_3 4 #Convert an iterator into an iterator5L = [1,2,3,4,5]6  forIinchL:7     Print(i)8 Print(ITER (L))#built-in function iter = = L._iter_ ()9 Print(L.__iter__())

Second, iterators

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

Iterators Implement for Loops

1 #!/usr/bin/env python2 #*_*_cod: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  whileTrue: Write your own equivalent for loop -     Try: -         Print(Next (l_iterator)) the     exceptstopiteration: -          Break

Summary:

#!/usr/bin/env python#*_*_cod:utf-8_*_#iterators are mostly used inside python, and we can just use them.#iterators: Built-in __iter__ and __next__ methods fromCollectionsImportiterable fromCollectionsImportIterator#An easy way to determine whether it is an iterator or an iterative object#s = ' abc '#Print (Isinstance (s,iterable)) s is not an iterative object#Print (Isinstance (s,iterator)) s is not an iterative object#Print (Isinstance (ITER (s), Iterator))

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.