#-*- coding:utf-8 -*- a=[1,2,3,4] for i,j in enumerate(a): print i,j '''只有ij时,''' a=[1,2,3,4] for i in enumerate(a): print i '''只有i 时,''' dic={1:'a',2:'c','d':4} for i in enumerate(dic): print i '''是字典时,对应得是key''' b=[1,2,4,5,6,7,] for index,i in enumerate(b): print index,i b[index]+=1 print(b) print('jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj') c=[1,2,4,6,7,8] c=map(lambda x:x+1,c) for i in c: print i print (type(c)) '''产生的是一个list所以要循环打印,''' l=[j+1 for j in range(10)] print l print (type(l)) '''产生的是一个list生产序列''' g=(j+1 for j in range(10)) print g #这里这句打印的是g生成器的内存地址 print (type(g)) #print g.next()调用生成器的.next()可以显示生成器里的计算出来的元素, # 但一次调用只能显示一个元素,可以采用for循环来显示所有元素.可迭代对象 for i in g: print i print('jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj') '''斐波那函数的编程 def fib(max): n,a,b=0,0,1 while n<max: print b a,b=b,a+b n+=1 fib(10) ''' def pluse (a,b): print (a+b) def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n += 1 data=fib(10) print (data.next()) print (data.next()) pluse(100,200) print (data.next()) print ('hahahhhahhahha') print (data.next()) print (data.next()) print (data.next())
凡是可作用于for
循环的对象都是Iterable
类型;
凡是可作用于next()
函数的对象都是Iterator
类型,它们表示一个惰性计算的序列;
集合数据类型如list
、dict
、str
等是Iterable
但不是Iterator
,不过可以通过iter()
函数获得一个Iterator
对象。
Python的for
循环本质上就是通过不断调用next()
函数实现的
#-*- coding:utf-8 -*- from collections import Iterator print (isinstance((),Iterator)) print (isinstance([],Iterator)) print (isinstance('adf',Iterator)) print (isinstance([i *2 for i in range(10)],Iterator)) print (isinstance((i *2 for i in range(10)),Iterator))#是生成器 #可以直接用于for循环的对象为可迭代对象 print ('jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj') from collections import Iterable print (isinstance((),Iterable)) print (isinstance([],Iterable)) print (isinstance({},Iterable)) print (isinstance('adf',Iterable)) print (isinstance([i *2 for i in range(10)],Iterable)) print (isinstance((i *2 for i in range(10)),Iterable))#是生成器 #可以直接被next()函数调用并不断返回下一个值得对象称为迭代器
l=[1,2,6,8,9]
It=iter(l)
print It
print (isinstance(It,Iterator))