python 生成器

# 生成器

a = [x*2 for x in range(10)]
print(a)

# 通过生成器,生成你想要的列表,
# 等你什么时候用,什么时候生成


# 生成器的第一种表现形式 ()

b = (x*2 for x in range(10))
# print(next(b))
# print(next(b))
# print(next(b))
# print(next(b))
# print(next(b))
# print(next(b))
# print(next(b))
# print(next(b))
# print(next(b))
# print(next(b))
# print(next(b))

# 生成器的第二种变现形式

# 交互两个变量的值
a,b = 0,1
b,a = b,a


a,b = b,a+b
# 斐波拉契数列
def creatNum():
a,b = 0,1
for i in range(5):
print(b)
a,b = b,a+b

 

# 如果函数中有yield,就不是函数了,成生成器了
def creatNum():
print("-------start--------")
a,b = 0,1
for i in range(5):
yield b #生成器
a,b = b,a+b
print("-------stop--------")

'''()生成器对象'''
a = creatNum()

# 生成器对象==的特点:仅仅保存了一套生成生成这个特殊序列的算法,并没有让这个算法现在就去执行,而是调用他才执行。

def creatNum2():
print("-------start--------")
a,b = 0,1
for i in range(5):
print("-------1--------")
yield b #生成器
print("-------2--------")
a,b = b,a+b
print("-------3--------")
print("-------stop--------")

# 创建了一个生成器对象
# b = creatNum2();

# 让b这个生成器对象快开始执行,如果第一次执行,那么就从creatNum2的开始部分执行
# 如果是之前执行过了,那么久从上一次停止的位置开始执行,执行到yield停止,并返回后面的值
# next(b) #的值
# # -------start--------
# # -------1--------
# next(b)
# # -------2--------
# # -------3--------
# # -------1--------
# next(b)
# # -------2--------
# # -------3--------
# # -------1--------
# next(b)
# # -------2--------
# # -------3--------
# # -------1--------
# next(b)
# # -------2--------
# # -------3--------
# # -------1--------
# next(b)
# # -------2--------
# # -------3--------
# # -------1--------
# next(b)
# -------stop--------
# Traceback (most recent call last):
# File "生成器.py", line 87, in <module>
# next(b)
# StopIteration


# 用迭代器循环他,生成器可以放在循环中
# for num in creatNum2():
# print(num)

# for num in a:
# print(num)

# 注意
# next(a) 等价于 a.__next__()
# ret = a.__next__()
# print(ret)

 


def test():
i = 0
while i<5:
temp = yield i
print(temp)
i+=1

t = test()

# 第一次不能直接调send("hahah"),可以使用t.send(None)
# t.send("哈哈") #的值
# Traceback (most recent call last):
# File "生成器.py", line 128, in <module>
# t.send("哈哈")
# TypeError: can't send non-None value to a just-started generator

# t.__next__() # None

# 第一次调用t.send(None)
t.send(None)
# 1

# t.send()
# File "生成器.py", line 136, in <module>
# t.send()
# TypeError: send() takes exactly one argument (0 given)


# t.__next__() # None
# t.__next__() # None
# t.__next__() # None

# t.send("哈哈") # 哈哈 把一个值赋值给yield i

 


# 生成器的作用 # 多任务。看上去同时执行的任务

# 多任务 ===3种 协程 进程 线程


# 以下代码相当于协程
def test1():
while True:
print("---1---")
yield None


def test2():
while True:
print("---2---")
yield None

t1 = test1()
t2 = test2()

while True:
print("11111")
t1.__next__()
t2.__next__()

 

 

 

# 两个值在没有第三个变量的情况下怎么交换
a = 9
b = 10
a = a + b
b = a - b
a = a - b

 

posted @ 2018-08-07 20:47  红尘陌上,独自行走  阅读(119)  评论(0编辑  收藏  举报