设为首页 加入收藏

TOP

迭代器,可迭代对象,生成器(一)
2017-10-23 06:06:58 】 浏览:180
Tags:对象 成器

可迭代对象(iterable),迭代器(iterator),生成器(generator)

 例子

>>> for key in {'k1':1}:
    print(key)

    
k1
>>> for i in [1,2,3]:
    print(i)

    
1
2
3
>>> for char in 'chc':
    print(char)



>>> with open('gy.txt','r') as f:
    for line in f:
        print(line)

        
This is my first text.

This is the first line.

This is the append text

 

可迭代对象有__iter__() 方法,迭代器有__iter__() 和__next__() 方法

对于上面的for 语句,for 语句会对容器对象调用iter()函数,这个函数return一个迭代器对象并且这个对象有__next__方法。每次访问容器对象都会返回一个元素。当后面没元素时,会引发 StopIteration Exception 去告诉for 尊还应该终止了。

 


 

迭代器:(iterator)

An iterator is an object representing a stream of data; this object returns the data one element at a time.

A Python iterator must support a method called __next__() that takes no arguments and always returns
the next element of the stream. If there are no more elements in the stream, __next__() must raise
the StopIteration exception. Iterators don’t have to be finite, though; it’s perfectly reasonable to write an
iterator that produces an infinite stream of data.

迭代器是一个代表一连串数据的对象,这个对象每次返回数据的一个元素。Python 迭代器必须有__call__()方法

,这个方法不带参数,总是返回这串数据的下一个数据,当在没有数据会引发StopIteration 异常。

迭代器不必是有限的,但写一个迭代器让他产生有限的数据是相当合理的。

迭代器的优点:

1提供了一种不依赖于索引的取值方式

2.惰性计算,节省内存

迭代器的缺点

1,取值不如按照索引取值方便

2,一次性的,只能往后走不能往前走

2无法获得长度

支持迭代器的数据类型

python 的序列类型sequence type,字典dictionary,文件对象file(readline),集合set

迭代器协议是指:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代 (只能往后走不能往前退)

可迭代对象:实现了迭代器协议的对象(如何实现:对象内部定义一个__iter__()方法)

for 循环本质就是遵循可迭代协议的访问方式

先调用object.__iter__()方法,

dic={0:[1,2,3],1:[4,5,6],2:[7,8,9]}
x=dic.__iter__()
x=dic[1].__iter__()
print(x.__next__())
print(x.__next__())
print(x.__next__())

调用__iter__()方法,就可以转得到迭代器。

 


 

生成器(generator)

生成器是一个创造迭代器简单且功能强大的工具,可以用常规的函数去写一个生成器,不过这个函数内部要有 yield 语句。

生成器会自动生成 __iter__ () 和__next__() method ,并且会自动保存程序状态。

 

generator expression 

>>> def f1():
    n=0
    while n<5:
        yield n
        n=n+1
    print('end')

    
>>> f=f1()
>>> f
<generator object f1 at 0x000000000316DF68>
>>> for item in f:
    print(item)

    
0
1
2
3
4
end
>>> hasattr(f,'__iter__')
True
>>> hasattr(f,'__next__')
True
>>> 

生成器表达式  generation expression  列表解析 list comprehensions 

>>> s=(i*i for i in range(5))
>>> s
<generator object <genexpr> at 0x000000000316DF10>

 list comprehension 用[] 抱起来   generator expression  用() 

>>> ls=[i*2 if i>3 else i*i for i in range(6)]
>>> ls
[0, 1, 4, 9, 8, 10]
>>> 

 pass values into a generator

In Python 2.4 and earlier, generators only produced output. Once a generator’s code was invoked to create
an iterator, there was no way to pass any new information into the function when its execution is resumed.
You could hack together this ability by making the generator look at a global variable or by passing in some
mutable object that callers then modify, but these approaches are messy.
In Python 2.5 there’s a simple way to pass values into a generator. yield became an expression, returning a
value that can be assigned to a variable or otherwise operated on:
val = (yield i)
I recommend that you always put parentheses around a yield expression when you’re doing something with
the returned value, as in the above

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇“羊车门”问题 下一篇起名字好难啊!(初识Django)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目