一、tuple迭代
a = (1,2,3,4)
for x in a:
print x
运行结果:
1
2
3
4
二、列表迭代
b = [1,2,3,4]
for x in b:
print x
运行结果:
1
2
3
4
三、字典迭代
(一)
c = {1:'a',2:'b',3:'c'}
for i,j in c.items():
print 'i=',i,'j=',j
print c.items
print c.items()
运行结果:
i= 1 j= a
i= 2 j= b
i= 3 j= c
<built-in method items of dict object at 0x00AC2780>(内建方法)
[(1, 'a'), (2, 'b'), (3, 'c')](调用实例)
类似的:c.key()/c.key/c.values()/c.values
(二)
c = {1:'a',2:'b',3:'c'}
for i,j in c.iteritems():
print 'i=',i,'j=',j
print c.iteritems
print c.iteritems()
运行结果:
i= 1 j= a
i= 2 j= b
i= 3 j= c
<built-in method iteritems of dict object at 0x00AC2780>(内建方法)
<dictionary-itemiterator object at 0x00AC57B0>(字典迭代器)
类似的:c.iterkey()/c.iterkey/c.itervalues()/c.itervalues
四、yield迭代
(一)函数中应用yield,使该函数(fun1)成为一个生成器,可进行迭代:
def fun1(alist):
for i in alist:
yield i+1
alist=[1,2,3,4]
for i in fun1(alist):
print i,
运行结果:
2 3 4 5
(二)Fibonacci数列
(1)def fab1(x):
a,b=0,1
while a<x:
print a,
a,b=b,a+b
print type(fab(30))
函数直接可以调用,生成具体值。
运行结果:
0 1 1 2 3 5 8 13 21 <type 'NoneType'>
(2)def fab(max):
a,b=0,1
while a<max:
yield a
a,b=b,a+b
for x in fab(30):
print x,
print type(fab(30))
因为有yield, fab(30)是一个生成器,可进行迭代。
运行结果:
0 1 1 2 3 5 8 13 21
<type 'generator'>
(3)迭代器的next()方法
def fun2():
yield 1
print 'enter'
print 'fun2().next=',fun2().next()
运行结果:
(3.1)输出顺序改变
fun2().next= 1
def fun2():
print 'enter'
yield 1
print 'fun2().next=',fun2().next()
运行结果:
fun2().next= enter
1
(3.2)多个yield情况,当进行到yield进行终端,后面的都没有运行,再次调用仍如此。
def fun2():
print 'enter'
yield 1
print 'next'
yield 2
print 'next again'
print 'fun2().next=',fun2().next()
print 'fun2().next=',fun2().next()
运行结果:
fun2().next= enter
1
fun2().next= enter
1