#Author by Andy
#_ *_ Coding:utf-8 _*_
Import time
From collections Import iterable
#列表生成式
def func ():
List=[]
For I in Range (10000000):
List.append (i)
Print (list)
#print (list)
#[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Generator= (I for I in range (10))
#print (Type (generator))
Def func1 ():
For I in generator:
Print (i)
Def Timmer ():
Time_start=time.time ()
Func1 ()
Time_stop=time.time ()
Print (Time_stop-time_start)
#定义斐波那契数列
def fib (max):
n,a,b=0,0,1
While n < max:
Print (b)
A,b=b,a+b
N=n+1
FIB (10)
# Note that the assignment statement:
# A, B = B, A + b
Equivalent to
# t = (b, A + b) # T is a tuple
# a = T[0]
# b = t[1]
def fib (max):
n,a,b=0,0,1
While n < max:
Yield b
A,b=b,a+b
N=n+1
Return ' Done '
F=FIB (10)
S= ' I am the dividing line '
Print (f.__next__ ())
Print (S.center (50, '-'))
Print (f.__next__ ())
Print (S.center (50, '-'))
#异常捕获
G=FIB (10)
While True:
Try
x = Next (g)
Print (x)
Except Stopiteration as E:
Print ("Generator got en error:", E.value)
Break
#############################################################
#通过yield实现在单线程的情况下实现并发运算的效果
DEF consumer (name):
Print ('%s ready to buy bread '%name)
While True:
Product=yield
Print ('%s bought bread%s '% (name,product))
Def producer ():
C1=consumer (' Han Meimei ')
C2=consumer (' Li Lei ')
C1.__next__ ()
C2.__next__ ()
For I in range (10):
Time.sleep (1)
Print (' bread%s and bread%s is out! '% (i,i+1))
C1.send (i)
C2.send (i+1)
#producer ()
# iterators
# An object that can be called by the next () function and continually returns the next value is called an iterator: Iterator.
#
# isinstance () determines whether an object is iterable to an object
# generators are iterator objects, but list, dict, and Str are iterable, but not iterator.
# Turn the list, Dict, str and other iterable into iterator can use the ITER () function
Print (Isinstance (generator,iterable))
#True
Python3 Generators & iterators