python 迭代器

一、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



转载于:https://my.oschina.net/wangfly/blog/262741

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值