#装饰器 # import time # def show_time(func): # def inner(*x): # start_time = time.time() # func(*x) # end_time = time.time() # print(end_time-start_time) # return inner # @show_time # def add(*x): # sum = 0 # for i in x: # sum+=i # time.sleep(1) # print(sum) # add(7, 8, 9)#列表生成 # t = ('123', 8, [1, 2, 3]) # d = {'leo':18, 'age':25} # def f(n): # n = n**3 # return n # list_builder = [x for x in range(10)]#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # list_builder2 = [x*2 for x in range(10)]#[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] # list_builder3 = [f(x) for x in range(10)]#[0, 1, 8, 27, 64, 125, 216, 343, 512, 729] # list_builder4 = [x for x in t]#['123', 8, [1, 2, 3]] # list_builder5 = [x for x in d]#['age', 'leo'] # print(list_builder) # print(list_builder2) # print(list_builder3) # print(list_builder4) # print(list_builder5)#生成器 #a = (x for x in range(5)) #print(a)#<generator object <genexpr> at 0x0120BB10> # print(next(a)) #等价于a.__next__() # #print(a.__next__()) # print(next(a)) # print(next(a)) # for i in a: # if i ==2: # print(i) # continue# def fibo(max): # n, before, after = 0, 0, 1 # while n < max: # #print(before) # yield before # before, after = after, before+after # n = n+1 # # g = fibo(10) # print(g)#<generator object fibo at 0x0107BB10> # print(next(g)) # def bar(): # print('ok') # cout = yield 1 # print(cout) # #print('ok2') # yield 2 # g =bar() #next(g) # g.send(None) # g.send('eeee')#迭代器iterator #生成器都是迭代器,迭代器不一定是生成器 #什么是迭代器:有两个方法:1.有Iter()方法,2.有next()方法 l = [1, 2, 3, 4, 5] d = iter(l) #print(d) #<list_iterator object at 0x00785A50> #print(len(d))#TypeError: object of type 'list_iterator' has no len() #for循环迭代出迭代器中的值 for i in range(len(l)): print(next(d)) from collections import Iterator,Iterable print(isinstance(l,list))#True,判断是否为List类型 print(isinstance(l,Iterable))#True,判断是否为可迭代对象 print(isinstance(l,Iterator))#False,判断是否为迭代器 print(isinstance(d,Iterator))#True,判断是否为迭代器
装饰器,生成器,迭代器
最新推荐文章于 2021-10-21 10:50:49 发布