美文网首页python_...
迭代器与生成器

迭代器与生成器

作者: plato_哲 | 来源:发表于2017-08-01 22:11 被阅读0次

手动遍历迭代器:

(遍历一个可迭代对像的所有元素,但不用for)
使用next()函数遍历:判断结束时,根据异常StopIteration或者给定指定值标记结尾。
两种:

def manual_iter():
    with open('demo1.txt') as f:
        try:
            while True:
                line= next(f)
                print(line,end="")
        except StopIteration:
            pass

指定None作为结尾标记

def manual_iter1():
    with open('demo1.txt') as f:
        while True:
            line=next(f,None)
            if line==None:
                break
            print(line,end="")

代理迭代:

des:自定义一个容器对象,里面包含列表、元组、或其他可迭代对象。
想要直接在对这个容器对象迭代操作。

class Node:
    def __init__(self,value):
        self.value=value
        self._children=[]
    def __repr__(self):
        return 'Node({!r})'.format(self.value)
    def add_child(self,node):
        self._children.append(node)
    def __iter__(self):
        return iter(self._children)
if __name__=="__main__":
    root=Node(0)
    child1=Node(1)
    child2=Node(2)
    root.add_child(child1)
    root.add_child(child2)
    #打印结果Node(1) Node(2)
    for ch in root:
        print(ch)

实现方法object.__iter__(self):
实现此方法返回iterator, iterator可以遍历容器对象里的所有对象 。
但是,在调用了上面调用了iter(self._children),就是把迭代请求传递给_children。
iter(object[,sentinel])中,返回iterator对象.如果没有第二个参数,object必须是collection object(此对象要支持迭代协议(实现__iter()__)),或者必须支持sequence protocol(实现__getitem()__),如果任何一个都不支持,那么抛出TypeError. 如果第二参数有,那么object必须是可调用的,iterator在每次调用__next__()时调用object, 如果返回的值是sentinel , StopIteration异常将会被抛出。

使用迭代器创建新的迭代

def frange(start,stop, increment):
    x=start
    while x<stop:
        yield x
        x+=increment
for n in frange(0,4,0.5):
         print(n)

yield生成iterator

相关文章

网友评论

    本文标题:迭代器与生成器

    本文链接:https://www.haomeiwen.com/subject/vglslxtx.html