标签:utf-8 ISE 一个 image turn 自定义 分享 技术 inf
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"
算法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()迭代列表中的元素
类似于迭代器
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生成
标签:utf-8 ISE 一个 image turn 自定义 分享 技术 inf
原文地址:https://www.cnblogs.com/xiaxiaoxu/p/9742261.html