1whileTrue#只是单纯地重复,因而不是迭代print'===>'1230while#迭代print1212'hello'123123'a'1'a''b''a.txt'3'a.txt''a.txt'43'a'1'b'2'c'3#得到迭代器对象,迭代器对象即有__iter__又有__next__#Trueprint#等同于next(iter_dic) 一次取一个值print#等同于next(iter_dic)print#等同于next(iter_dic)print#这次执行会抛出异常StopIteration,或者说结束标志#有了迭代器,我们就可以不依赖索引迭代取值了while1tryprintbreak#这么写太丑陋了,需要我们自己捕捉异常,控制next,python这么牛逼,能不能帮我解决呢?能,请看for循环4forfor'a'1'b'2'c'3forprintfor123251yieldprint'====>first'yield1print'====>second'yield2print'====>third'yield3print'====>end'print#<generator object func at 0x0000000002184360> 2print3yieldyieldprint"%s ready to eat"whileTrueyieldprint"%s eat %s"'sb'#对于表达式形式的yield,在使用时,第一次必须传None,g.send(None)等同于next(g)'面条''米饭''冒菜'4yieldyieldyieldreturn1yield2yield12345612return
,如需转载请自行联系原作者