标签:
names = iter([‘alex‘,‘wupeiqi‘,‘eva‘]) print(names) print(names.__next__()) print(names.__next__()) print(names.__next__()) #在往下取就报错 # print(names.__next__())
#ATM def cash_money(amount): while amount > 0: amount -= 100 yield 100 print(‘又来取钱啦!‘) #这里没有真正执行函数,只是把函数变成一个迭代器 atm = cash_money(500) # print(atm) print(atm.__next__()) print(atm.__next__()) print(‘叫个大保健‘) print(atm.__next__())
#消费者生产者模型 import time def consumer(name1): print(‘{name}准备吃包子啦!‘.format(name = name1)) while True: baozi = yield print(‘第{baozi_num}个包子来了,被{name}吃了!‘.format(baozi_num=baozi,name=name1)) def producer(name2): c = consumer(‘a‘) c2 = consumer(‘b‘) c.__next__() c2.__next__() print(‘{name}开始准备做包子啦!‘.format(name=name2)) for i in range(1,6): time.sleep(1) print(‘做了两个包子!‘) c.send(i) c2.send(i) producer(‘alex‘)
#列表解析 li = [i+100 for i in range(10)] print(li) #加条件 li2 = [i+100 for i in range(10) if i % 2 == 0] print(li2)
由于列表解析非常占内存,所以不适用大数据的场景
#生成器表达式 li = (i+100 for i in range(10)) print(li) #<generator object <genexpr> at 0x0000000000A2AE08> #加条件 li2 = (i+100 for i in range(10) if i % 2 == 0) for x in li2: print(x)
欢迎大家对我的博客内容提出质疑和提问!谢谢
笔者:拍省先生
标签:
原文地址:http://www.cnblogs.com/xinsiwei18/p/5616058.html