# 深入讲解python中的迭代器和生成器

__iter__()和next()方法

class myrange(object):
def __init__(self, n):
self.idx = 0
self.n = n
def __iter__(self):
return self
def next(self):
if self.idx < self.n: val = self.idx self.idx += 1 return val else: raise stopiteration() class myrange(object): def __init__(self, n): self.idx = 0 self.n = n def __iter__(self): return self def next(self): if self.idx < self.n: val = self.idx self.idx += 1 return val else: raise stopiteration()

myrange = myrange(3)
for i in myrange:
print i

class zrange:
def __init__(self, n):
self.n = n
def __iter__(self):
return zrangeiterator(self.n)
class zrangeiterator:
def __init__(self, n):
self.i = 0
self.n = n
def __iter__(self):
return self
def next(self):
if self.i < self.n: i = self.i self.i += 1 return i else: raise stopiteration() zrange = zrange(3) print zrange is iter(zrange) print [i for i in zrange] print [i for i in zrange]

next()方法的返回值就是yield语句处的参数（yielded value）

[expr for iter_var in iterable if cond_expr]

[i for i in range(50) if i%2]

(expr for iter_var in iterable if cond_expr)

def permutations(li):
if len(li) == 0:
yield li
else:
for i in range(len(li)):
li[0], li[i] = li[i], li[0]
for item in permutations(li[1:]):
yield [li[0]] + item
for item in permutations(range(3)):
print item
def permutations(li):
if len(li) == 0:
yield li
else:
for i in range(len(li)):
li[0], li[i] = li[i], li[0]
for item in permutations(li[1:]):
yield [li[0]] + item
for item in permutations(range(3)):
print item

send(value):

python 2.5中，yield语句变成了yield表达式，也就是说yield可以有一个值，而这个值就是send()方法的参数，所以send(none)和next()是等效的。同样，next()和send()的返回值都是yield语句处的参数（yielded value）

close():

itertools模块提供了一系列迭代器，能够帮助用户轻松地使用排列、组合、笛卡尔积或其他组合结构。

Posted in 未分类