迭代器iter():节省内存
Iter()迭代器
每一次输出下一个值
>>> a=iter(range(10))
>>> a.next()
0
>>> a.next()
1
>>> a.next()
2
可以用捕获异常来排除超出迭代范围,或者判断长度
>>> try:
... 1/0
... except:
... print "error occur"
...
error occur
如:
#encoding=utf-8
a=iter(range(10))
while 1:
try:
print a.next()
except:
print "error"
a=[1,2,3,4,5,6]变成字典{1:2,3:4,5:6}
算法1
#encoding=utf-8
a=[1,2,3,4,5,6]
d={}
for i in range(0,(len(a)-1),2):
print "i:",i
d[a[i]]=a[i+1]
print d
算法2
#encoding=utf-8
a=[1,2,3,4,5,6]
d={}
c=iter(a)
for i in range(len(a)/2):
k=c.next()
v=c.next()
d[k]=v
print d
自定义的迭代器
#encoding=utf-8
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)
print myRange.next()
print myRange.next()
print myRange.next()
print myRange.next()
结果:
生成器用圆括号声明类似列表推导
也节省内存
用括号生成
b=(x*x for x in range(10))
用b.next()迭代列表中的元素
类似于迭代器
也可以在函数内用yield,yield必须自函数内用
def odd():
print 'step 1'
yield 1
print 'step 2'
yield 3
print 'step 3'
yield 5
o = odd()
print o.next()
print o.next()
print o.next()
print o.next()
生成器和迭代器区别
迭代器用iter(),
生成器可以用圆括号,或者用yield生成