python/iterators and generators

Source: Internet
Author: User
Tags iterable

python/iterators and generators one, iterators
迭代器的特性:    迭代是Python中最强有力的特性之一,可以把迭代看成是一种处理序列中元素的方式。    可以直接作用于for循环的对象统称为可迭代对象(Iterable)。    可以被next()函数调用并不断返回下一个值的对象称为迭代器(Iterator)。        所有的Iterable均可以通过内置函数iter()来转变为Iterator。    出可迭代对象的个数会报错StopIteration,是一个结束信号迭代器的优点:        1、迭代器提供一种不依赖于索引的取值方式,这样就可以遍历那些没有索引的对象了(字典、集合、文件)    2、迭代器和列表比较,迭代器是惰性计算,更节约内存迭代器的缺点:    1、永远不能获取迭代器的长度,使用不如列表索引取值灵活 2、一次性的,只能往后取值,不能往前,不能像索引一样取得指定位置的值
Ii. ways to view iterators and iterators
    from collections import iterable,iterator s= ' hello ' l=[1,2,3] t= ( Span class= "Hljs-number" >1,2,3) d={  ' a ': 1} set1={1, 2,3,4} f=open (  ' a.txt ')  #都是可迭代, as long as the object has a __iter__ () method, are iterative s.__iter__ () l.__iter__ () t.__iter__ () d.__iter__ () Set1 . __iter__ () f.__iter__ ()  #查看是否可以迭代的 print (Isinstance (s,iterable))  #查看是否是迭代器, only the file is an iterator f.__next__ () print (Isinstance (f,iterator))     
Iii. manual access to elements in iterators 1, issues
我们要处理某个可迭代对象中的元素,但是基于某种原因不能也不想使用for循环。
2. Solutions
要手动访问可迭代对象中的元素,可以使用next()函数,然后自己编写代码来捕获stopiteration异常。例如:
#!/usr/bin/env python#-*-Coding:utf-8-*-With open (' passwd ',' R ', encoding=' UTF8 ')as F: while True: try:line=next (f) Print (Line,end=") except Stopiteration: break #一般来说, stopiteration exception is used to inform us of the end of the iteration, however, If you are manually executing next (), you can also command him to return a value, such as None, as follows: with Open ( ' passwd ', Span class= "hljs-string" > ' R ', Encoding= ' UTF8 ') as F: while true:line=next (F,None) if line is none: break print (Line,end=      
  In most cases, we use the for loop to access the elements in an iterative object, but Occasionally, there is a need for finer-grained control over the underlying iteration mechanism. Therefore, it is necessary to understand what is actually happening in the iteration. The for loop is also the first to use the ITER method to generate an iterator to the object to be cycled, and then go through the iterator and iterate through each element in the iterator    
>>> items=[1,2,3]>>> i=iter(items) #===> i.__iter__()>>> next(i) #===> i.__next__()1>>> next(i)2>>> next(i)3>>> next(i)Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration
Iv. Generators
The 
  Builder is a function that contains the yield keyword, and when it is called, the code in the function does not execute and returns an iterator. Each time a value is requested, the code in the generator executes until it encounters a yield or return statement, yield statement one will generate a value, return statement a generator to stop execution (not generate anything, return statements can be called without arguments only when used in a generator in other words, the generator is composed of two parts: the generator's function and the generator's iterator, and the generator's function uses the def definition, including yield section, the generator iterator is the part returned by this function. 
def countdown (n): print ( ' starting to count from ', N) while n> 0: yield n n-=1 print ( ' done! ') G=countdown (5) print (Next (g)) print (Next (g)) print (Next (g)) print (Next (g))  #执行结果如下starting to count from 5< Span class= "Hljs-number" >5432< Span class= "Hljs-number" >1 #函数中出现了yield语句, this function is converted to the genetic builder. Unlike normal functions, the generator will only run in response to an iterative operation. Calls need to use the next method to execute, not executed once, when the next yield will be stopped, the next time you execute next, will be executed from the current yield, know that encountered a yield     
生成器的本质就是一个迭代器,同时也是一个函数,调用的方式和函数类似,yield也相当于函数中的return    yield和return的区别:return只能返回一次函数就会彻底结束,而yield能返回多次值yield到底干了什么事情: 1、yield把函数变成生成器(迭代器),把iter和next方法封装在函数内部 2、函数在暂停一及继续下一次运行时的状态是yield保存
Five, the co-process
From Urllib.requestImport UrlopenDefInit(func):def wrapper  (*args,**kwargs): Res=func (*args,**kwargs) Next (res) return Res return wrapper @init def get (): while Span class= "Hljs-keyword" >true:url=yield res=urlopen (URL). Read () print (res) g=get () Span class= "hljs-comment" > #g是一个迭代器 # next (g) #这里使用一个init的装饰器, automatically doing next work g.send ( "http://www.baidu.com")  #使用send把括号内的URL传递给yieldg. Send ( ' http://www.python.org ') g.send ( ' http://www.163.com ')    
协程函数,是把yield改为表达式的方式,改过send代替next给yield传值e.send于next(e)的区别    1、如果函数内yield是表达式形式,那么必须先next(e),让生成器在第一个yield位置处等着 2、二者的共同之处都可以让函数在上次暂停的位置继续运行,不一样的地方在于,send在触发一下次代码的执行时,给yield传值

python/iterators and generators

Related Article

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.