#_author:Administrator
#date:2019/11/3
#1.列表生成式
a=[x for x in range(10)]
print(a)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a1=[x*x for x in range(10)]
print(a1)#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
def f(n):
return n**3
a2=[f(x) for x in range(10)]
print(a2)#[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
#(2)
a3=(1,'123')
a,b=a3
print(a,b)#1 123
#2.生成器
#(1)
b=(x*2 for x in range(5))
print(b)#<generator object <genexpr> at 0x01061F70>
print(next(b))#0 等价与s._next_(),in python2 b.next()
print(next(b))# 2
print(next(b))
print(next(b))
print(next(b))
print('-----------')
# print(next(b)) StopIteration
#生成器就是一个可迭代对象 Iterable
s=(x for x in range(5))
for i in s:#垃圾回收机制,判断异常(是否到最后一个元素)
print(i)
print('-----------')
#(2)生成器有2种创建方式
#(2-1)b=(x*2 for x in range(5))
#(2-2)yield
def fun():#只要一个函数有yield ,则fun()就是一个生成器对象
print('ok')
yield 1
print('ok2')
yield 2
m=fun()#此处生成了一个生成器对象
print(m)#<generator object fun at 0x036B2230>
next(m)#ok
next(m)#ok2
# next(m) StopIteration 因为函数末尾有 return None
print('-----------')
for i in fun():
print(i)
# ok
# 1
# ok2
# 2
#for循环后可以跟:可迭代对象
#什么是可迭代对象:内部有iter()方法的
#如:
se=(1,2,3)
se.__iter__()
list=[1,3,5]
list.__iter__()
dic={'star':'123'}
dic.__iter__()
print('---------')
def fibo(max):
n,before,after=0,0,1
while n < max:
print(after)
before,after=after,before+after
n=n+1
fibo(8)
Output:
1
1
2
3
5
8
13
21