迭代器和生成器

迭代器和生成器

最简单实现的一个迭代器.

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
#coding:utf-8
items = [1, 2, 3]
it = iter(items)
print next(it)
print next(it)
print next(it)
print next(it)

output

1
2
3
4
5
6
7
8
python iter_and_generate.py
1
2
3
Traceback (most recent call last):
File "iter_and_generate.py", line 10, in <module>
print next(it)
StopIteration

自定义迭代器

只需要一个具有next方法的类,只要能够提供返回迭代器实例的__iter__特殊方法

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyIterator(object):
def __init__(self, step):
self.step = step
def next(self):
if self.step == 0:
raise StopIteration
self.step -= 1
return self.step
def __iter__(self):
return self
for el in MyIterator(4):
print el

itertools模块中好玩的迭代器

islice:窗口迭代器

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
#coding:utf-8
import itertools
def starting_at_five():
value = raw_input().strip()
while value != '':
for el in itertools.islice(value.split(), 4, None):
yield el
value = raw_input().strip()

tee:往返式的迭代器

1
2
3
def with_head(iterable, headsize=1):
a, b = itertools.tee(iterable)
return list(itertools.islice(a, headsize)), b

groupby:uniq迭代器

使用行程长度编码(RLF)来压缩数据

1
2
3
4
5
6
7
from itertools import groupby
def compress(data):
reutrn ((len(list(group)), name) \
for name, group in groupby(data)
def decompress(data):
return (car * size for size, car in data)

生成器

使得函数需要返回一系列元素的函数变得更加简单,高效.

Ex

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python
#coding:utf-8
def fibonacci():
a, b = 0, 1
while True:
yield b
a, b = b, a+b
fib = fibonacci()
# print fib.next()
print [fib.next() for i in range(10)]

在处理大的文件的时候,这种方式比较节省内存

关于yield,以及yeild更多姿势

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
#coding:utf-8
def psychologist():
print "请告诉我你的问题?"
while True:
answer = (yield)
if answer is not None:
if answer.endswith('?'):
print("不要想太多问题")
elif "good" in answer:
print("A that\'s good, go on")
elif 'bad' in answer:
print("Don'\t be so negative")
free = psychologist()
free.next()
free.next()
free.next()
free.send("why I show?")
free.send("good")
free.send("bad")

send()的工作机制和next()一样。但是yield将变成能够返回传入的值。

在python3.x中,yield有更多的用法。

坚持技术分享,您的支持将鼓励我继续创作!